【问题标题】:Number prototype to work with int and float [duplicate]与 int 和 float 一起使用的数字原型 [重复]
【发布时间】:2018-11-23 16:31:47
【问题描述】:

我想写一个原型来格式化数字。 2 个浮点数和逗号分隔符。

我在下面写了原型。

使用浮动。

    1.1.toBRLCurrency()
    // "1,10"

但它确实不起作用 int。

    1.toBRLCurrency()
    // Uncaught SyntaxError: Invalid or unexpected token

我注意到有趣的是(int 和 float)都返回类型号。

    typeof 1.1
    // "number"

    typeof 1
    // "number"

我不知道我错过了什么。 这是我的代码。

Number.prototype.toBRLCurrency = function(){
    var options = {
        'minimumFractionDigits':2,
        'maximumFractionDigits': 2
    }
    return this.toLocaleString('pt-BR',options);
}

var n = 1.1;
console.log( n, typeof n ); 
console.log(1.1.toBRLCurrency());

n = 1;
console.log( n, typeof n ); 
//console.log(1.toBRLCurrency())

【问题讨论】:

  • 数字是基元。你需要创建一个普通的方法。
  • (1).toBRLCurrency() — 您必须处理 . 被解析为数字文字的一部分这一事实。
  • 谢谢@Pointy!
  • 或者直接使用n.toBRLCurrency()

标签: javascript number-formatting


【解决方案1】:

感谢@Pointy!

(1).toBRLCurrency()

Number.prototype.toBRLCurrency = function(){
    var options = {
        'minimumFractionDigits':2,
        'maximumFractionDigits': 2
    }
    return this.toLocaleString('pt-BR',options);
}

var n = 1.1;
console.log( n, typeof n ); 
console.log(1.1.toBRLCurrency());

n = 1;
console.log( n, typeof n ); 
console.log((1).toBRLCurrency())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 2018-10-12
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多