Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

677
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda