如何创建新的MathContext?

时间:2012-01-06 03:18:43

标签: javascript bigdecimal

主要问题

我正在使用this BigDecimal,我正在尝试创建一个新的MathContext对象以传递给BigDecimal的divide()方法。但我尝试过的一切都抛出异常,说它是未定义的。以下是我尝试工作的一些例子:

context = new MathContext();                            // ReferenceError: MathContext is not defined
context = new BigDecimal.MathContext();                 // TypeError: undefined is not a function
context = new BigDecimal.prototype.MathContext();       // TypeError: undefined is not a function
a = new BigDecimal('1'); context = new a.MathContext(); // TypeError: undefined is not a function

我做错了什么? (顺便说一句,我尝试过的每个搜索引擎都会返回Java的结果,而不是Javascript,尽管我的第一个关键字是javascript。)

背景

我正在尝试解决this question I asked earlier。我已经确定问题是BigDecimal以我不想要的方式舍入答案。在使用调试器跟踪代码时,似乎我需要将MathContext对象作为第二个参数传递给divide()方法。这是我的代码中的相关片段(暂时忽略魔术数字):

// v1 and v2 are both of type BigDecimal.
v1 = v1.divide(v2, new MathContext(0, 0, false, 4));

任何其他解决我问题的方法都是可以接受的,但我仍然想了解为什么我不能做new MathContext()

1 个答案:

答案 0 :(得分:2)

我认为只是创建

的第一个例子
context = new MathContext(...)

是正确的。至少它在我的例子here中工作。我直接从github包含BigDecimal库:

<script type="text/javascript" src="https://raw.github.com/dtrebbien/BigDecimal.js/master/build/BigDecimal-all-last.js"></script>