快速将双精度值四舍五入到x小数位数

本文翻译自:Rounding a double value to x number of decimal places in swift

Can anyone tell me how to round a double value to x number of decimal places in Swift? 谁能告诉我在Swift中如何将双精度值四舍五入到小数点后位数x?

I have: 我有:

var totalWorkTimeInHours = (totalWorkTime/60/60)

With totalWorkTime being an NSTimeInterval (double) in second. totalWorkTime是NSTimeInterval(双精度),以秒为单位。

totalWorkTimeInHours will give me the hours, but it gives me the amount of time in such a long precise number eg 1.543240952039...... totalWorkTimeInHours将给我小时,但是它给了我这么长的精确时间,例如1.543240952039 ......

How do I round this down to, say, 1.543 when I print totalWorkTimeInHours ? 在打印totalWorkTimeInHours时如何将其四舍五入为1.543?


#1楼

参考:https://stackoom.com/question/1qi0j/快速将双精度值四舍五入到x小数位数


#2楼

Not Swift but I'm sure you get the idea. 不是Swift,但是我敢肯定,您会明白的。

pow10np = pow(10,num_places);
val = round(val*pow10np) / pow10np;

#3楼

How do I round this down to, say, 1.543 when I print totalWorkTimeInHours ? 在打印 totalWorkTimeInHours 如何将其四舍五入为1.543?

To round totalWorkTimeInHours to 3 digits for printing, use the String constructor which takes a format string: 要将totalWorkTimeInHourstotalWorkTimeInHours为3位以进行打印,请使用String构造函数,该构造函数采用format字符串:

print(String(format: "%.3f", totalWorkTimeInHours))

#4楼

You can use Swift's round function to accomplish this. 您可以使用Swift的round函数来完成此操作。

To round a Double with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000: 要以3位精度四舍五入一个Double ,请先将其乘以1000,四舍五入,然后将四舍五入的结果除以1000:

let x = 1.23556789
let y = Double(round(1000*x)/1000)
print(y)  // 1.236

Other than any kind of printf(...) or String(format: ...) solutions, the result of this operation is still of type Double . 除了任何类型的printf(...)String(format: ...)解决方案之外,此操作的结果仍为Double类型。

EDIT: 编辑:
Regarding the comments that it sometimes does not work, please read this: 关于有时无效的评论,请阅读以下内容:

What Every Computer Scientist Should Know About Floating-Point Arithmetic 每个计算机科学家都应了解的浮点运算法则


#5楼

Building on Yogi's answer, here's a Swift function that does the job: 在Yogi的答案的基础上,这是完成任务的Swift函数:

func roundToPlaces(value:Double, places:Int) -> Double {
    let divisor = pow(10.0, Double(places))
    return round(value * divisor) / divisor
}

#6楼

A handy way can be the use of extension of type Double 一种方便的方法是使用Double类型的扩展名

extension Double {
    var roundTo2f: Double {return Double(round(100 *self)/100)  }
    var roundTo3f: Double {return Double(round(1000*self)/1000) }
}

Usage: 用法:

let regularPie:  Double = 3.14159
var smallerPie:  Double = regularPie.roundTo3f  // results 3.142
var smallestPie: Double = regularPie.roundTo2f  // results 3.14
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值