我需要这种格式:
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有什么想法吗?
发布于 2015-12-13 10:21:47
问题是如何使用format
new Intl.NumberFormat("es-ES").format(current.toFixed(2));
^^^^^^^^^^^^^^^^^^对current.toFixed(2)的调用将返回一个已经有2位小数位的string实例。
对带有字符串实例的NumberFormat.prototype.format的调用将导致它将字符串转换回一个数字,然后根据es-ES区域性规则对其进行格式化,从而丢失有关固定小数位格式的信息。
相反,使用指定NumberFormat的options对象实例化minimumFractionDigits。
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 );
}https://stackoverflow.com/questions/34250000
复制相似问题