简体   繁体   English

在BigDecimal除法中使用MathContext对象

[英]Using MathContext objects in BigDecimal divide method

I am writing test cases with the JavaScript BigDecimal library by Daniel Trebbien (specifically the BigDecimal-all-last.min.js ) and I can't seem to use the MathContext object in the divide method without throwing the error "MathContext() Bad form value" 我正在使用Daniel TrebbienJavaScript BigDecimal库 (特别是BigDecimal-all-last.min.js )编写测试用例,并且在不抛出错误“ MathContext()Bad”的情况下,似乎无法在除法中使用MathContext对象形式价值”

Since this library is a direct port from Java, I am using this documentation . 由于该库是Java的直接端口,因此我正在使用本文档 Since both the "form" (parameter #2) and "rounding mode" (parameter #4) are just constants, I don't understand why I am getting a "bad form value" error. 由于“表格”(参数2)和“取整模式”(参数4)都是常量,因此我不明白为什么会出现“表格格式错误”错误。 My Webstorm IDE sees the constants just fine so I know they are there. 我的Webstorm IDE看到的常量很好,所以我知道它们在那里。 Changing "form" constants to "ENGINEERING" or any of the others does not fix the issue. 将“ form”常量更改为“ ENGINEERING”或其他任何方法都无法解决该问题。

var mc = new MathContext(3, BigDecimal.PLAIN, false, BigDecimal.ROUND_HALF_EVEN);
var two = new BigDecimal("2");
var seven = new BigDecimal("7");
var twoSevenths = two.divide(seven, mc); // constructor divide(BigDecimal, MathContext)
console.log(twoSevenths.toString()); // expecting 0.286

Do you see anything I am doing wrong? 您看到我做错了什么吗?

** **

UPDATE UPDATE

There ARE other divide constructors one could use of course, but the multiple re-use of a single MathContext object would be ideal for a Tiny JavaScript project and thus is the focus here. 当然,还有其他划分构造函数可以使用,但是单个MathContext对象的多次重用对于Tiny JavaScript项目是理想的,因此这里是重点。

** **

There is a small typo in your code. 您的代码中有一个小的错字。 The PLAIN constant is actually defined in MathContext , so the first line should be: PLAIN常量实际上是在MathContext定义的,因此第一行应为:

var mc = new MathContext(3, MathContext.PLAIN, false, BigDecimal.ROUND_HALF_EVEN);

With this fix, "0.286" is logged to the console as expected. 使用此修复程序,“ 0.286”被记录到控制台按预期方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM