Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

enter image description here

Yes, I don't want anything after the decimal point in my output.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!