[英]JavaScript regex - Format decimal with trailing zero and string
我有不同的价格格式,需要显示如下:
1.09-----> 1.09
1.00----> 1
1.00 lb --->1lb
1.09 lb---->1.09lb
我需要构建JavaScript正则表达式以指定格式显示以上价格的帮助。
使用parseFloat
和Number.toString
解析并格式化数字部分。 添加特殊情况以处理LB:
function formatPrice(price) {
return parseFloat(price) + (price.match(/ .+$/) ? price.match(/ (.+)$/)[1] : "");
}
console.log(formatPrice("1.00")); // 1
console.log(formatPrice("1.09")); // 1.09
console.log(formatPrice("1.09000")); // 1.09
console.log(formatPrice("1.00 lb")); // 1lb
console.log(formatPrice("1.09 lb")); // 1.09lb
console.log(formatPrice("1.09 kg")); // 1.09kg
您可以尝试以下正则表达式,
> "1.09 lb".replace(/\.00|\s+/g, "");
'1.09lb'
> "1.00 lb".replace(/\.00|\s+/g, "");
'1lb'
> "1.00".replace(/\.00|\s+/g, "");
'1'
> "1.09".replace(/\.00|\s+/g, "");
'1.09'
要删除两个以上的零,
> "1.000".replace(/\.00+|\s+/g, "");
'1'
你可以试试
\.0+\s*(\D*)$|[ ]+
补发: $1
这是在线演示
样例代码:
var re = /\.0+\s*(\D*)$|[ ]+/g;
var str = '1.09\n1.00\n1.00 lb\n1.09 lb';
var subst = '$1';
var result = str.replace(re, subst);
输出:
1.09
1
1lb
1.09lb
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.