Scala和Java BigDecimal [英] Scala and Java BigDecimal
问题描述
我想从我的应用程序中的基于数学模块的Java切换为脚本语言。这是由于mathy Java的可读性和功能限制。
例如,在Java中,我有这个:
BigDecimal x = new BigDecimal(1.1);
BigDecimal y = new BigDecimal(1.1);
BigDecimal z = x.multiply(y.exp(new BigDecimal(2));
正如你所看到的,没有BigDecimal运算符重载,简单的公式会变得很复杂。
使用双精度时,这看起来很好,但我需要精度。
我希望在Scala中能做到这一点:
var x = 1.1;
var y = 0.1;
print(x + y);
默认情况下,我会得到类似于小数的行为,唉Scala不会默认使用小数计算。
然后我在Scala中这样做: var x = BigDecimal(1.1);
var y = BigDecimal(0.1);
println(x + y);
我仍然得到一个不准确的结果。
也许我应该使用Groovy来最大限度地提高可读性(默认情况下它使用小数)?
我不知道Scal a,但是在Java 新的BigDecimal(1.1)中使用
double 初始化
BigDecimal
code>的价值,因此它不是正好等于1.1。在Java中,您必须改用新的BigDecimal(1.1)
。也许这对Scala也有帮助。
I want to switch from Java to a scripting language for the Math based modules in my app. This is due to the readability, and functional limitations of mathy Java.
For e.g, in Java I have this:
BigDecimal x = new BigDecimal("1.1");
BigDecimal y = new BigDecimal("1.1");
BigDecimal z = x.multiply(y.exp(new BigDecimal("2"));
As you can see, without BigDecimal operator overloading, simple formulas get complicated real quick.
With doubles, this looks fine, but I need the precision.
I was hoping in Scala I could do this:
var x = 1.1;
var y = 0.1;
print(x + y);
And by default I would get decimal-like behaviour, alas Scala doesn't use decimal calculation by default.
Then I do this in Scala:
var x = BigDecimal(1.1);
var y = BigDecimal(0.1);
println(x + y);
And I still get an imprecise result.
Is there something I am not doing right in Scala?
Maybe I should use Groovy to maximise readability (it uses decimals by default)?
I don't know Scala, but in Java new BigDecimal(1.1)
initializes the BigDecimal
with a double
value and thus it is not exactly equal to 1.1. In Java you have to use new BigDecimal("1.1")
instead. Maybe that will help in Scala as well.
这篇关于Scala和Java BigDecimal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!