斯卡拉双打和精准 [英] Scala Doubles, and Precision

查看:98
本文介绍了斯卡拉双打和精准的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个可以截断或舍入Double的功能?在我的代码中,我想要一个数字: 1.23456789 四舍五入到 1.23

解决方案

您可以使用 scala.math.BigDecimal

 code> BigDecimal(1.23456789).setScale(2,BigDecimal.RoundingMode.HALF_UP).toDouble 

还有一些其他舍入模式,不幸的是目前还没有很好的记录(尽管他们的Java等价物是)。


Is there a function that can truncate or round a Double? At one point in my code I would like a number like: 1.23456789 to be rounded to 1.23

解决方案

You can use scala.math.BigDecimal:

BigDecimal(1.23456789).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble

There are a number of other rounding modes, which unfortunately aren't very well documented at present (although their Java equivalents are).

这篇关于斯卡拉双打和精准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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