【问题标题】:NumberFormat won't respect .toFixedNumberFormat 不会尊重 .toFixed
【发布时间】: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


    【解决方案1】:

    问题在于你如何使用format

    new Intl.NumberFormat("es-ES").format(current.toFixed(2));
                                          ^^^^^^^^^^^^^^^^^^
    

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

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

    相反,使用指定minimumFractionDigitsoptions 对象来实例化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(例如,如果将格式化字符串用作价格)。
    • 我好像没有在IOS工作,ReferenceError: Can't find variable: Intl有什么解决方法吗?
    • @ToniMichelCaubet 您使用的是什么版本的 iOS? Intl 是 ECMAScript/JavaScript 的一个相对较新的补充。
    • 我暂时解决了,检测IOS并追加cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.es,你怎么看?
    猜你喜欢
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多