[英]Replace with regex for min/max decimal length
I've found on this forum the following regex to replace any number into the smallest possible decimal length: 我在这个论坛上发现了以下正则表达式,可以将任何数字替换为最小的十进制长度:
number.toFixed(maxDecimal).replace(/\\.?0+$/, '');
It works really well, except for one case: when number is equal to 49.9999999, it returns 5 instead of 50 when I put maxDecimal to 0. I'm a little bit lost with regex and would appreciate if you come up with a suggestion. 它非常有效,除了一种情况:当数字等于49.9999999时,当我将maxDecimal设置为0时,它返回5而不是50。我对regex有点迷失了,如果您提出建议,我们将不胜感激。
Just remove the question mark ?
只是删除问号
?
since that makes 50
reduce to 5
because the regex says 0 or 1 occurrence of decimal point followed by 1 or more 0
's. 因为正则表达式说0或1出现小数点,然后是1或多个
0
,所以将50
减少到5
。 You don't want that because 0 in 50 would match that 0+ part because decimal point is optional. 您不希望这样,因为50中的0会匹配那个0+部分,因为小数点是可选的。 Use this regex this to make sure you replace only decimal part aptly.
使用此正则表达式可确保仅适当地替换小数部分。
>47.79955965.toFixed(5).replace(/(\.0+){0,1}$/, '');
"47.79956"
>number=49.9999999
49.9999999
> number.toFixed(5).replace(/(\.0+){0,1}$/, '');
"50"
> number.toFixed(0).replace(/(\.0+)?$/, '');
"50"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.