简体   繁体   中英

Rounding Mode in Number() method in Javascript

I'm rewriting the JavaScript code to Java. I came across this line in JavaScript code.

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.

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.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. 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.

Just to be clear, Number.prototype.toFixed() is not equivalent to 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). I believe "Math.ceil" and "Math.floor" are the method names in both JS and 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).

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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