如何让 Scala BigDecimal 显示大量数字? [英] How do I get Scala BigDecimal to display a large number of digits?

查看:44
本文介绍了如何让 Scala BigDecimal 显示大量数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下操作

  val num = BigDecimal(1.0)
  val den = BigDecimal(3.0)
  println((num/den)(MathContext.DECIMAL128))

我只知道

0.3333333333333333333333333333333333

小于我想要的 128

推荐答案

默认上下文是 MathContext.DECIMAL128,它用于所有计算,因此在您的示例中,num/den 的结果已经四舍五入到 128 位.您需要先为所有值设置上下文,然后再进行计算.

The default context is MathContext.DECIMAL128 which is used in all computations so in your example the result of num/den is already rounded to 128 places. You need to set your context on all values first and then do your computations.

val mc = new MathContext(512)
val num = BigDecimal(1.0,mc)
val den = BigDecimal(3.0,mc)
println(num/den)

不要尝试使用 MathContext.UNLIMITED,除非您知道您的算术不会产生无界十进制表示.甚至在您尝试打印之前它就会爆炸.

Don't try and use MathContext.UNLIMITED unless you know your arithmetic does not produce an unbounded decimal representation. It will blow up even before you try to print.

这篇关于如何让 Scala BigDecimal 显示大量数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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