Formatting a truncated float in JavaScript

#javascript #stackoverflow

Written by Anders Marzi Tornblad

StackOverflow user nips asked how to format a floating point number in JavaScript, truncating the value instead of rounding it.

According to the question, this was the desired result:

The developer.mozilla.org page gives a thorough example of how to perform decimal rounding correctly, avoiding any rounding errors in the process. For this question, however, a simple multiplication-division pair is surely good enough:

// truncate-and-format.js

// Step by step
var multiplied = value * 100;
var truncated  = Math.floor(multiplied);
var divided    = truncated * 0.01;
var output     = divided.toFixed(2);

// One-liner version
var output = (Math.floor(value * 100) * 0.01).toFixed(2);

The above code performs the following steps, in order:

Most languages do have functions called round, ceil, floor or similar ones, but almost all of them round to the nearest integer, so the multiply-round-divide chain (or divide-round-multiply for rounding to tens, hundreds, thousands...) is a good pattern to know.

In JavaScript there is no float datatype like in a lot of other languages, but the Number type is used for both integers and floating point numbers. Internally, numbers are just 64 bit floating point numbers (source: ecma262-5.com), conforming to the IEEE 754 standard. So when dealing with numbers in JavaScript, you always need to take floating point precision into consideration!