[英]How can I printf a Perl bignum without losing precision?
#!/usr/bin/perl
use strict;
use warnings;
my $s = "1234567890.123456789";
{
no bignum; printf "bignum==%s\n", bignum::in_effect() // 0;
my $x = $s;
printf "%29s\n", $x;
printf "%29.9f\n\n", $x;
}
{
use bignum; printf "bignum==%s\n", bignum::in_effect() // 0;
my $x = $s;
printf "%29s\n", $x;
printf "%29.9f\n\n", $x;
}
My Perl's printf (ActiveState v5.10.1 built for darwin-thread-multi-2level) using the %f conversion doesn't honor my value past the 1e-6 digit, even when using bignum: 使用%f转换的My Perl的printf(为darwin-thread-multi-2level构建的ActiveState v5.10.1)不会使我的值超过1e-6数字,即使使用bignum:
$ t.pl
bignum==0
1234567890.123456789
1234567890.123456717
bignum==1
1234567890.123456789
1234567890.123456717
How can I print my input without losing precision? 如何在不丢失精度的情况下打印输入?
My real problem is that I'm going to need to manipulate this number (eg, $x/0.000_000_001, or, worse, $x/0.000_001_024, which I can't fake with substr() function calls), but the current abatement has stumped me before I can even get to the "fun" part. 我真正的问题是我需要操纵这个数字(例如,$ x / 0.000_000_001,或者更糟糕的是,$ x / 0.000_001_024,我不能用substr()函数调用来伪装),但是在我能够进入“有趣”部分之前,目前的减少让我感到难过。
Perl's printf
doesn't really do bignums. Perl的printf
并不真正做bignums。 Use one of the Math::BigFloat methods for getting a string. 使用Math :: BigFloat方法之一获取字符串。 Since doing 自从做
my $x = $s;
just copies the string, you'll have to do something like 只要复制字符串,你就必须做类似的事情
my $x = 0+$s;
so that $x
is a Math::BigFloat. 所以$x
是一个Math :: BigFloat。 Then something like 然后像
printf "%29s\n", $x->ffround(-9);
should do what you want. 应该做你想做的事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.