简体   繁体   中英

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

eg 10.00 should be 10 only and not 10.00.

.toFixed() converts your result to String ,
so you need to make it back a Number: jsBin demo

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM