1

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?

Nips
  • 13,162
  • 23
  • 65
  • 103

2 Answers2

6

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.

Anders Marzi Tornblad
  • 18,896
  • 9
  • 51
  • 66
  • You could also perform a **bitwise or** with zero, but I have always felt that the `floor` function is easier to read and understand when dealing with real numbers and not, say, bitfields. – Anders Marzi Tornblad Feb 17 '16 at 12:08
  • 1
    There is nothing wrong with the answer. The only thing wrong is where I tapped! I pushed the wrong button and didn't realise until now. Sorry. In the meantime the answer got locked and I can't correct it now. If you could please make a simple edit (anything), the lock will be removed and I will be able to upvote instead. Sorry again. – Arman Ozak Feb 17 '16 at 13:06
  • 1
    Thanks a lot Anders. Nice answer by the way. – Arman Ozak Feb 17 '16 at 13:11
1

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));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 2
    If you're going to make a method you might as well put `toFixed` in there and calculate `100` with `Math.pow` **(almost correct, but there's no reason to calculate the same `Math.pow(10, p)` twice!)**. – h2ooooooo Feb 17 '16 at 12:03