在 Swift 中获取双精度的小数部分 [英] Getting the decimal part of a double in Swift

查看:26
本文介绍了在 Swift 中获取双精度的小数部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 swift 中分离 double 的小数部分和整数部分.我尝试了多种方法,但它们都遇到了相同的问题...

I'm trying to separate the decimal and integer parts of a double in swift. I've tried a number of approaches but they all run into the same issue...

let x:Double = 1234.5678
let n1:Double = x % 1.0           // n1 = 0.567800000000034
let n2:Double = x - 1234.0        // same result
let n3:Double = modf(x, &integer) // same result

有没有办法在不将数字转换为字符串的情况下获得 0.5678 而不是 0.567800000000034?

Is there a way to get 0.5678 instead of 0.567800000000034 without converting to the number to a string?

推荐答案

无需将其转换为字符串,您可以四舍五入到多个小数位,如下所示:

Without converting it to a string, you can round up to a number of decimal places like this:

let x:Double = 1234.5678
let numberOfPlaces:Double = 4.0
let powerOfTen:Double = pow(10.0, numberOfPlaces)
let targetedDecimalPlaces:Double = round((x % 1.0) * powerOfTen) / powerOfTen

你的输出是

0.5678

这篇关于在 Swift 中获取双精度的小数部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆