JavaScript Number.toLocaleString() with 4 digits after separator

帅比萌擦擦* 提交于 2019-11-30 00:06:38

问题


Is there a way to get number.toLocaleString() with 4 digits after the comma?

Example:

var number = 49.9712;
document.getElementById('id').innerText = number.toLocaleString();

Result: 49,9712

But now it always returns number with 2 digits after comma: 49,97


回答1:


You may use second argument to provide some options. In your case, with default locale:

number.toLocaleString(undefined, { minimumFractionDigits: 4 })



回答2:


I found that

var number = 49.9712;
number.toLocaleString( { minimumFractionDigits: 4 })

gave the result of "49.971"

In order to actually get the 4 decimal place digits, I did this:

number.toLocaleString(undefined, { minimumFractionDigits: 4 })

Also filling in a country code worked:

number.toLocaleString('en-US', { minimumFractionDigits: 4 })

In both cases I got 49.9712 for the answer.




回答3:


You cannot do this with toLocaleString() alone. But you can round to 4 decimal places before displaying:

var n = Math.round(number * 10000) / 10000;
document.getElementById('id').innerText = n.toLocaleString();



回答4:


If you need to use Locale settings than I don't think you'll be able to specify that you need 4 decimal places, but you can obviously do this using other prototype methods, such as toFixed().

Here's an example:

var number = 12.3456
number.toFixed(4)


来源:https://stackoverflow.com/questions/24758817/javascript-number-tolocalestring-with-4-digits-after-separator

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