【发布时间】: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