Skip to main content
JavascriptNumbers

JavaScript: Working with Numbers

By March 19, 2019July 5th, 2021No Comments

Good Reads

  1. https://medium.com/swlh/how-to-round-to-a-certain-number-of-decimal-places-in-javascript-ed74c471c1b8
  2. https://stackoverflow.com/a/48764436/6275860

Advise

When performing any arithmetic operations such as addition. Always check if the candidate number variables are not Nan. Otherwise, the result becomes a NaN.

1
2
3
parseFloatReplaceNaNByZero(item) {
    return (!isNaN(parseFloat(item)) ? parseFloat(item) : 0)
},

What is JavaScript equivalent for number_format in PHP?


1
2
3
4
5
6
7
8
9
// Lodash to rescue

// Works exactly as we expect. Output is a typeof number.
_.round("10.608", 2); // 10.61

// Following returns the output as string. That's one major down side.
parseFloat("10").toFixed(2); // 10.00
parseFloat("10.60").toFixed(2); // 10.60
parseFloat("10.605").toFixed(2); // 10.61