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

I have a line in Perl containing a small number: $ num = "0.00000001";

When I do a numerical operation on it, it becomes an exponential number: $ num = $ num * 100; print "$ num \ n";

Result: 1e-06

The question is how to get this number to print in floating point format, i.e. 0.000001.

I know that I can do this for a specific number using sprintf ("%. 6f", $ num), but I would like to have a general solution, so I don’t have to determine how many digits will be displayed after the decimal point each time (for example, 6 in the above example sprintf)

+4
source share
2 answers

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

If you just type or gate the number, it uses the default format, which, as you saw, leads to "1e-06" . Using sprintf with the format "%f" will give you a reasonable result; sprintf("%f", $num) gives "0.000001" .

But the format "%f" may lose information. For instance:

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

prints:

 0.000000 

You say you want to print without each time determining how many digits will be displayed after the decimal point. Something must make this definition, and there is no universally correct way to do this. The obvious thing is to print only significant numbers, omitting trailing zeros, but this creates some problems. How many digits do you print for 1.0/3.0 whose decimal representation has an infinite 3 s sequence? And 0.00000001 cannot be represented exactly in binary floating point:

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

prints:

 0.000000 0.000000010000000000000000209225608301284726753266340892878361046314239501953125 
+5
source

Use rodents of unusual size :

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

Source: https://habr.com/ru/post/1387363/


All Articles