在Perl中,如何限制小数点后的位数但没有尾随零?

Bri*_*ton 5 perl printf decimal-point

这个问题类似于"从浮点数中删除尾随'.0',但对于Perl和小数点后的最大位数.

我正在寻找一种方法将数字转换为字符串格式,删除任何冗余的'0',包括不仅仅是在小数点后面.并且仍然具有最大数字数字,例如3

输入数据是浮点数.期望的输出:

0         -> 0
0.1       -> 0.1
0.11      -> 0.11
0.111     -> 0.111
0.1111111 -> 0.111
Run Code Online (Sandbox Code Playgroud)

vla*_*adr 18

直接使用以下内容:

my $s = sprintf('%.3f', $f);
$s =~ s/\.?0*$//;

print $s
Run Code Online (Sandbox Code Playgroud)

...或者定义一个子程序来更一般地执行它:

sub fstr {
  my ($value,$precision) = @_;
  $precision ||= 3;
  my $s = sprintf("%.${precision}f", $value);
  $s =~ s/\.?0*$//;
  $s
}

print fstr(0) . "\n";
print fstr(1) . "\n";
print fstr(1.1) . "\n";
print fstr(1.12) . "\n";
print fstr(1.123) . "\n";
print fstr(1.12345) . "\n";
print fstr(1.12345, 2) . "\n";
print fstr(1.12345, 10) . "\n";
Run Code Online (Sandbox Code Playgroud)

打印:

0
1
1.1
1.12
1.123
1.123
1.12
1.12345
Run Code Online (Sandbox Code Playgroud)


Rya*_*ght 3

您还可以使用Math::Round来执行此操作:

$ perl -MMath::Round=nearest -e 'print nearest(.001, 0.1), "\n"'
0.1
$ perl -MMath::Round=nearest -e 'print nearest(.001, 0.11111), "\n"'
0.111
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案仅适用于少数人。`print` 在 15 位数字后删除小数部分或完全转换为科学记数法;`nearest` 可以放大数字中已经存在的任何错误(例如,使用 `nearest` 将 `111111111129995.56` 舍入为 `.001` 会生成 `111111111129995.58`,而 `sprintf("%.3f", 111111111129995.56)` 会正确生成 `111111111129 995.56` .) (2认同)