简体   繁体   English

Javascript 中 Number() 方法中的舍入模式

[英]Rounding Mode in Number() method in Javascript

I'm rewriting the JavaScript code to Java. I came across this line in JavaScript code.我正在将 JavaScript 代码重写为 Java。我在 JavaScript 代码中遇到了这一行。

Number("<amount-values>").toFixed(0)

As the value is related to money, I'm using BigDecimal in Java in order to make accurate calculations and not to lose any precisions.由于价值与金钱有关,我在 Java 中使用 BigDecimal 以进行准确计算而不丢失任何精度。

Could you please help me with the correct Rounding mode in BigDecimal that is equivalent to rounding mode of Number() method in JavaScript, where both the rounding's will produce the same result.你能帮我解决 BigDecimal 中正确的舍入模式吗?它等同于 JavaScript 中 Number() 方法的舍入模式,这两种舍入都会产生相同的结果。

BigDecimal.setScale(0)

Both the scalings are producing different results when there are decimals.当有小数时,两种缩放都会产生不同的结果。 Created a very small table and I see that Number() method is aligning with HALF_DOWN, HALF_EVEN, HALF_UP.创建了一个非常小的表,我看到 Number() 方法与 HALF_DOWN、HALF_EVEN、HALF_UP 对齐。 But this is very small example and there could be many number of other cases.但这是非常小的例子,可能还有很多其他情况。

在此处输入图像描述

Yes, I don't want anything after the decimal point in my output.是的,我不想要我的 output 中小数点后的任何内容。

Just to be clear, Number.prototype.toFixed() is not equivalent to Math.Round需要说明的是,Number.prototype.toFixed() 不等同于 Math.Round

 (5.5).toFixed(0) == 6
 (5.4).toFixed(0) == 5
 (-5.5).toFixed(0) === **-6**

 Math.round(5.5) == 6
 Math.round(5.4) == 5
 Math.round(-5.5) == **-5**

You should know this and decide what behavior you want, if any negative values are involved.如果涉及任何负值,您应该知道这一点并决定您想要什么行为。

If all your values are positive, the logic is pretty simple: if the decimal is greater than or equal to.5 then you round up (Math.ceil), otherwise you round down (Math.floor).如果您的所有值都是正数,则逻辑非常简单:如果小数点大于或等于 .5,则向上舍入 (Math.ceil),否则向下舍入 (Math.floor)。 I believe "Math.ceil" and "Math.floor" are the method names in both JS and Java.我相信“Math.ceil”和“Math.floor”是 JS 和 Java 中的方法名称。

Since you have decimals in your example, you need to be clear if you actually want the behavior as showcased by (-5.5).toFixed(0) vs Math.round(-5.5).由于您的示例中有小数,因此您需要弄清楚您是否真的想要 (-5.5).toFixed(0) 与 Math.round(-5.5) 所展示的行为。

It seems that toFixed effectively brings things on either side of 0 back towards 0. Math.round on the other hand seems to round the values down, to a lower values (either less positive, or more negative).似乎 toFixed 有效地将 0 两侧的东西带回到 0。另一方面,Math.round 似乎将值向下舍入到较低的值(要么不那么积极,要么更消极)。

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

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