6

I need to format numbers to two decimal digits in javascript. In order to do this I am using toFixed method which is working properly.

But in cases, where numbers don't have any decimal digits, it should not show decimal point

e.g. 10.00 should be 10 only and not 10.00.

ajm
  • 12,863
  • 58
  • 163
  • 234

2 Answers2

13

.toFixed() converts the result to String,
so you need to convert it back to Number:

parseFloat( num.toFixed(2) )

or by simply using the Unary +

+num.toFixed(2)

both will give the following:

//   15.00   --->   15
//   15.20   --->   15.2

If you only want to get rid of the .00 case, than you can go for String manipulation using .replace()

num.toFixed(2).replace('.00', '');

Note: the above will convert your Number to String.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • `+(num.toFixed(2))` is less to type. ;-) – RobG Jan 10 '15 at 12:59
  • But this doesn't do exactly what was asked, 10 -> 10, 10.111 -> 10.11 but 10.1 -> 10.1 and I would have expected 10.10 if the format is to be 2 dp except for whole numbers? I would have thought something like this `num.toFixed(2).split('.00', 1)` – Xotic750 Jan 10 '15 at 13:12
  • @Xotic750—agree, but the OP has chosen it. Don't you mean `num.toFixed(2).split('.00')[0]`? There's also `num.toFixed(2).replace('.00','')`. – RobG Jan 10 '15 at 13:16
  • @RobG They would also work, here is a [`jsFiddle`](http://jsfiddle.net/kjphefaL/) using my suggestion. [`split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) using the `limit` argument. – Xotic750 Jan 10 '15 at 13:19
  • 1
    @Xotic750— *split* returns an array, so you're relying on *toString* when it's assigned via *textContent*. It works, but I think explicitly selecting the member is better. And there will only be one `.00` anyway. – RobG Jan 10 '15 at 13:24
  • @RobG True, I was relying on `toString` to do the conversion, so yes being explicit would be better. Need more coffee. :) – Xotic750 Jan 10 '15 at 13:27
4

As an alternative to make this change global(if you need, of course), try this:

var num1 = 10.1;
var num2 = 10;

var tofixed = Number.prototype.toFixed;

Number.prototype.toFixed = function(precision)
{
    var num = this.valueOf();

    if (num % 1 === 0)
    {
        num = Number(num + ".0");
    }

    return tofixed.call(num, precision);
}

console.log(num1.toFixed(2));
console.log(num2.toFixed(2));

Fiddle. This is a mix of this and this post.

Community
  • 1
  • 1
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105