【发布时间】:2016-03-18 22:16:48
【问题描述】:
我需要这种格式:
555.555.55,55
555.555.55,50 /* Note te extra zero */
我正在尝试这样
new Intl.NumberFormat("es-ES").format(current.toFixed(2));
但这会打印出来
555.555.55,5
有什么想法吗?
【问题讨论】:
标签: javascript number-formatting
我需要这种格式:
555.555.55,55
555.555.55,50 /* Note te extra zero */
我正在尝试这样
new Intl.NumberFormat("es-ES").format(current.toFixed(2));
但这会打印出来
555.555.55,5
有什么想法吗?
【问题讨论】:
标签: javascript number-formatting
问题在于你如何使用format:
new Intl.NumberFormat("es-ES").format(current.toFixed(2));
^^^^^^^^^^^^^^^^^^
对current.toFixed(2) 的调用将返回一个已经有2 个小数位的string 实例。
使用字符串实例调用NumberFormat.prototype.format 将导致它将字符串转换回数字,然后根据es-ES 文化规则对其进行格式化,从而丢失有关固定小数位格式的信息。
相反,使用指定minimumFractionDigits 的options 对象来实例化NumberFormat:
new Intl.NumberFormat("es-ES", { minimumFractionDigits: 2 } ).format( current );
如果您要重复使用它,请记住缓存您的 Intl.NumberFormat 对象,这样您就不会每次都重新创建它:
const esFormat = new Intl.NumberFormat("es-ES", { minimumFractionDigits: 2 } ).format( current );
async function doSomething() {
const someNumericValue = await getNumber();
if( typeof someNumericValue !== 'number' || isNaN( someNumericValue ) ) throw new Error( someNumericValue + " is not a number." )
return esFormat.format( someNumericValue );
}
【讨论】:
maximumFractionDigits 设置为 2(例如,如果将格式化字符串用作价格)。
ReferenceError: Can't find variable: Intl有什么解决方法吗?
Intl 是 ECMAScript/JavaScript 的一个相对较新的补充。