ajm
ajm

Reputation: 13223

How to format numbers in javascript to two decimal digits?

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.

Upvotes: 6

Views: 9757

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206595

.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.

Upvotes: 14

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

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.

Upvotes: 4

Related Questions