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

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

问题描述

我正在尝试快速分隔双精度数的十进制和整数部分.我尝试了多种方法,但是它们都遇到了相同的问题...

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

0.5678

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

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