Nips
Nips

Reputation: 13880

How to format float?

I have float numbers:

var a = parseFloat("12.999");
var b = parseFloat("14");

And I want to display them as:

12.99
14.00 -> with zeros

But without round, only truncate. How to do it?

Upvotes: 1

Views: 179

Answers (2)

Anders Marzi Tornblad
Anders Marzi Tornblad

Reputation: 19305

You use a combination of the Math.floor() and Number.prototype.toFixed() function, like this:

console.log((Math.floor(a * 100) * 0.01).toFixed(2));
console.log((Math.floor(b * 100) * 0.01).toFixed(2));

Math.floor() will truncate the value to the closest lower integer. That is why you need to first multiply by 100 and then multiply by 0.01.

Number.prototype.toFixed() will format your output using a set number of decimals.

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.

Upvotes: 6

Nina Scholz
Nina Scholz

Reputation: 386660

You can first truncat the part, you do not need.

function c(x, p) {
    return ((x * Math.pow(10, p) | 0) / Math.pow(10, p)).toFixed(p);
}

document.write(c(12.999, 2) + '<br>');
document.write(c(14, 2));

Upvotes: 1

Related Questions