Formatting Number in javascript using decimal

☆樱花仙子☆ 提交于 2019-12-12 20:26:14

问题


I have following types of values in a, b,c,d.

a= 12345678
b= 12345678.098
c=12345678.1
d=12345678.11

I need to format like,

a = 12,345,678.000
b=  12,345,678.098
c=12,345,678.100
d=12,345,678.110

I already tried tolocaleString() and toFixed(3) method. But I'm not able to works together of both method.

need your suggestion on this.


回答1:


var num = 123456789;
console.log(num.toLocaleString(undefined, {minimumFractionDigits: 3, maximumFractionDigits: 3}));

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

undefined will use user's locale, you might want to specify a custom one.


Updated answer

var number = 12345678;
console.log(parseInt(number*1000).toLocaleString("en-US").replace(/\,([^\,]*)$/,"."+'$1'));



回答2:


Use Intl.NumberFormat,

var number = 12345678.098;
alert(new Intl.NumberFormat().format(number));

Here's a FIDDLE



来源:https://stackoverflow.com/questions/46401854/formatting-number-in-javascript-using-decimal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!