简体   繁体   中英

How to change exponential number format to the floating-point format in Perl

I have a string in Perl that contains a small number: $num = "0.00000001";

When I make a numeric operation on it, it becomes number in exponential format: $num = $num * 100; print "$num\\n";

The result is: 1e-06

The question is, how to get this number be printed in floating-point format, ie 0.000001.

I know I can do it for specific number with sprintf("%.6f", $num), but I'd like to have a generic solution, so I won't have to determine each time how many digits to show after the decimal point (like 6 in the above sprintf example)

When you apply a numeric operation to $num , it becomes a floating-point number. 1e-06 and 0.000001 are textual representations of that number; the stored value doesn't distinguish between them.

If you simply print or stringify the number, it uses a default format which, as you've seen, results in "1e-06" . Using sprintf with a format of "%f" will give you a reasonable result; sprintf("%f", $num) yields "0.000001" .

But the "%f" format can lose information. For example:

$num = "0.00000001";
printf("%f\n", $num);

prints:

0.000000

You say you want to print without having to determine each time how many digits to show after the decimal point. Something has to make that determination, and there's no universally correct way to do so. The obvious thing to do is print just the significant digits, omitting trailing zeros, but that presents some problems. How many digits do you print for 1.0/3.0 , whose decimal representation has an infinite sequence of 3 s? And 0.00000001 can't be represented exactly in binary floating-point:

$num = "0.00000001";
printf("%f\n", $num);    
printf("%.78f\n", $num);

prints:

0.000000
0.000000010000000000000000209225608301284726753266340892878361046314239501953125

Use rodents of unusual size :

$ perl -Mbigrat -E'$num = 0.00000001; $num *= 100; say $num'
0.000001

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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