如何在Swift中将小数位截断到x个位置 [英] How to truncate decimals to x places in Swift

查看:105
本文介绍了如何在Swift中将小数位截断到x个位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的swift程序中,我有一个非常长的十进制数字(例如 17.9384693864596069567 ),我想将十进制数截断到几个小数位(所以我想要输出为 17.9384 )。我不想将数字四舍五入为 17.9385 。我该怎么办?

In my swift program, I have a really long decimal number (say 17.9384693864596069567) and I want to truncate the decimal to a few decimal places (so I want the output to be 17.9384). I do not want to round the number to 17.9385. How can I do this?

我们很高兴!

注意:这不是重复的,因为它们是在完成其中一些功能之前,请使用旧版本的swift。另外,他们使用浮点数和整数,而我正在谈论双精度数。并且他们的问题/答案要复杂得多。

Note: This is not a duplicate because they are using a very old version of swift, before some of these functions were made. Also, they are using floats and integers, whereas I am talking about doubles. And their question/answers are much more complicated.

推荐答案

通过将其扩展为 Double

extension Double
{
    func truncate(places : Int)-> Double
    {
        return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
    }
}

您可以这样使用它

var num = 1.23456789
// return the number truncated to 2 places
print(num.truncate(places: 2))

// return the number truncated to 6 places
print(num.truncate(places: 6))

这篇关于如何在Swift中将小数位截断到x个位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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