简体   繁体   English

正则表达式使非十进制数为十进制(加.00)

[英]Regex to make nondecimal number decimal (add .00)

I have an user input where user can edit price of something. 我有一个用户输入,用户可以在其中输入价格。 To leave data consistance I would like to manipulate with that string on front-end site. 为了保持数据一致性,我想在前端站点上使用该字符串进行操作。

What I want to do is: 我想做的是:

1234 to 1234.00
12.3 to 12.30
12,3 to 12.30
1234.45 to 1234.45

So basicly, 所以基本上

  1. Replace comma with dots this should be done easy with somehing like: 用点替换逗号,这应该可以很容易地完成,例如:

     str.replace(',', '.'); 
  2. Add dots if number if not decimal and also always change number of digits on two(so add 0 if needed) I try to do something like: 如果不是十进制数,则添加点,并且总是更改两位数(因此,如果需要,则添加0),我尝试执行以下操作:

     priceByUser = priceByUser.replace(/^\\d*\\.?\\d*$/, "$1\\.00"); 

unfortunately this really doesnt even work as I expected. 不幸的是,这确实不符合我的预期。

Is there a chance someone can help me to solve this issue? 有人可以帮助我解决此问题吗? Thanks 谢谢

You could consider using a regular expression to replace your commas and periods with just decimal points and then parse the values as floats via parseFloat() then finally, use the toFixed(2) function to indicate that you want two decimal places : 您可以考虑使用正则表达式用小数点代替逗号和句点,然后通过parseFloat()将值解析为浮点数,然后最后使用toFixed(2)函数指示您想要两个小数位:

// This will clean up your input (consolidating periods and commas), parse the result
// as a floating point number and then format that number to two decimal places
priceByUser = parseFloat(priceByUser.replace(/,/g,'.')).toFixed(2);

If you wanted an extra-level of validation, you could consider stripping out any non-digit or decimal places after this occurs : 如果您需要额外的验证级别,可以考虑在发生这种情况后去除任何非数字或小数位:

// Sanitize
priceByUser = priceByUser.replace(/,/g,'.').replace(/[^\d\.]/g,'');
// Parse and format
priceByUser = Number(priceByUser).toFixed(2);

Example

You can see a working example here and and example of input/output below : 您可以在此处看到一个工作示例 ,以及下面的输入/输出示例:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM