首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NumberFormat不尊重.toFixed

NumberFormat不尊重.toFixed
EN

Stack Overflow用户
提问于 2015-12-13 10:14:00
回答 1查看 1.9K关注 0票数 5

我需要这种格式:

代码语言:javascript
复制
555.555.55,55
555.555.55,50 /* Note te extra zero */

我试着像这样

代码语言:javascript
复制
new Intl.NumberFormat("es-ES").format(current.toFixed(2));

但这个印出来了

代码语言:javascript
复制
555.555.55,5

有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-13 10:21:47

问题是如何使用format

代码语言:javascript
复制
new Intl.NumberFormat("es-ES").format(current.toFixed(2));
                                      ^^^^^^^^^^^^^^^^^^

current.toFixed(2)的调用将返回一个已经有2位小数位的string实例。

对带有字符串实例的NumberFormat.prototype.format的调用将导致它将字符串转换回一个数字,然后根据es-ES区域性规则对其进行格式化,从而丢失有关固定小数位格式的信息。

相反,使用指定NumberFormatoptions对象实例化minimumFractionDigits

代码语言:javascript
复制
new Intl.NumberFormat("es-ES", { minimumFractionDigits: 2 } ).format( current );

如果要重用Intl.NumberFormat对象,请记住缓存它,这样就不会每次都重新创建它:

代码语言:javascript
复制
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 );
}
票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34250000

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档