[英]JavaScript regex - Format decimal with trailing zero and string
I have different format of prices, which needs to be displayed as below: 我有不同的价格格式,需要显示如下:
1.09-----> 1.09
1.00----> 1
1.00 lb --->1lb
1.09 lb---->1.09lb
I need help in building the regex for JavaScript to display the above prices in specified formats. 我需要构建JavaScript正则表达式以指定格式显示以上价格的帮助。
Parse and format the numeric portion using parseFloat
and Number.toString
. 使用
parseFloat
和Number.toString
解析并格式化数字部分。 Add a special case to handle LBs: 添加特殊情况以处理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
You could try the below regex, 您可以尝试以下正则表达式,
> "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'
To remove more than two zero's, 要删除两个以上的零,
> "1.000".replace(/\.00+|\s+/g, "");
'1'
You can try 你可以试试
\.0+\s*(\D*)$|[ ]+
Replacement : $1
补发:
$1
Here is online demo 这是在线演示
Sample code: 样例代码:
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);
output: 输出:
1.09
1
1lb
1.09lb
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.