Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby正则表达式对尾随零进行四舍五入_Ruby_Regex_Fractions_Decimal Point - Fatal编程技术网

Ruby正则表达式对尾随零进行四舍五入

Ruby正则表达式对尾随零进行四舍五入,ruby,regex,fractions,decimal-point,Ruby,Regex,Fractions,Decimal Point,我正在寻找一个正则表达式来从十进制数中删除尾随的零。它应返回以下结果: 0.0002300 -> 0.00023 10.002300 -> 10.0023 100.0 -> 100 1000 -> 1000 0.0 -> 0 0 -> 0 基本上,如果分数部分为0,则应删除尾随零和尾随小数点。当该值为0时,它还应返回0。有什么想法吗?谢谢。试试正则表达式: (?:(\..*[^0])0+|\.0+)$ 并将其替

我正在寻找一个正则表达式来从十进制数中删除尾随的零。它应返回以下结果:

0.0002300 -> 0.00023
10.002300 -> 10.0023
100.0     -> 100
1000      -> 1000
0.0       -> 0
0         -> 0
基本上,如果分数部分为0,则应删除尾随零和尾随小数点。当该值为0时,它还应返回0。有什么想法吗?谢谢。

试试正则表达式:

(?:(\..*[^0])0+|\.0+)$
并将其替换为:

\1
演示:

tests = ['0.0002300', '10.002300', '100.0', '1000', '0.0', '0']
tests.each { |tst|
  print tst, " -> ", tst.sub(/(?:(\..*[^0])0+|\.0+)$/, '\1'), "\n"
}
产生:

0.0002300 -> 0.00023
10.002300 -> 10.0023
100.0 -> 100
1000 -> 1000
0.0 -> 0
0 -> 0
或者您可以简单地执行
%g”%tst
来删除尾随的零:

tests = ['0.0002300', '10.002300', '100.0', '1000', '0.0', '0']
tests.each { |tst|
  s = "%g" % tst
  print tst, " -> ", s, "\n"
}
它产生相同的输出。

只是另一种方式

["100.0","0.00223000"].map{|x|"%g"%x}

我认为这比它需要的复杂得多,但它的工作原理是如此+1:),我完全同意@Mark。我盯着它看了一会儿,但看不到一条捷径…谢谢,这太棒了!您的解决方案“%g”%x只有6个字符!