最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to format numbers in javascript to two decimal digits? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Jan 10, 2015 at 12:31 ajmajm 13.2k59 gold badges168 silver badges240 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 14

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

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.

发布评论

评论列表(0)

  1. 暂无评论