## Formatting a truncated float in JavaScript

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 value
`12.999`

must be displayed as`12.99`

- The value
`14`

must be displayed as`14.00`

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:

- Value is multiplied by 100
`12.999 => 1299.9`

`14 => 1400`

- Value is truncated using the
`Math.floor`

function`1299.9 => 1299`

`1400 => 1400`

- Value is multiplied by 0.01
`1299 => 12.99`

`1400 => 14`

- Value is formatted for printing using two decimal places using the
`Number.prototype.toFixed`

function`12.99 => "12.99"`

`14 => "14.00"`

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-6.com)*,
conforming to the IEEE 754 standard. So when dealing with numbers
in JavaScript, you **always** need to take floating point precision into consideration!

Posted by
Category JavaScript
Labels

Tweet this