简体   繁体   English

十进制js将三位数字四舍五入[可能是错误?]

[英]decimal js rounding 3digit numbers [probably a bug?]

I'm using the decimal.js to calculate with numbers and using the advantages by handling big numbers.. 我正在使用decimal.js来计算数字,并通过处理大数字来利用其优势。

Now i came to the point where i want to round numbers to a specific multiplicator. 现在我到了要把数字四舍五入到特定乘法器的地步。

everything worked fine, until i found this issue; 一切正常,直到我发现这个问题;

new Decimal(750).toNearest(500,3).toNumber() //-> 500

this line will output 500. Is it simply a bug or did I made a fault in my code? 该行将输出500。这仅仅是一个错误还是我的代码出错了? And if its a fault i'm wondering why its happening only at this specific numbers showed below... 如果这是一个错误,我想知道为什么仅在下面显示的特定数字下会发生...

new Decimal(75).toNearest(50,2).toNumber() //-> 100
new Decimal(7500).toNearest(5000,4).toNumber() //-> 10'000

when u play a little bit with these statements at decimal.js API 当您在十进制.js API上使用这些语句时

only the 3 digit number could be round correctly: 只有3位数可以正确取整:

new Decimal(300).toNearest(200,3).toNumber() //-> 200
new Decimal(450).toNearest(300,3).toNumber() //-> 300
new Decimal(600).toNearest(400,3).toNumber() //-> 400

Please care of the second property in .toNearest-function: https://mikemcl.github.io/decimal.js/#modes 请注意.toNearest-function中的第二个属性: https ://mikemcl.github.io/decimal.js/#modes

2: Rounds towards Infinity (up) 2:向无穷大方向舍入(向上)
3: Rounds towards -Infinity (down) 3:朝-Infinity倒数(向下)
4: Rounds towards nearest neighbour. 4:向最近的邻居舍入。 If equidistant, rounds away from Zero. 如果等距,则从零舍入。

So you have to think about what the expected result should be and choose the correct rounding method. 因此,您必须考虑预期的结果,然后选择正确的舍入方法。 The rounding method has nothing to do with the number of digits. 四舍五入方法与位数无关。

new Decimal(75).toNearest(50,2).toNumber() //-> 100
new Decimal(75).toNearest(50,3).toNumber() //-> 50
new Decimal(75).toNearest(50,4).toNumber() //-> 100

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

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