How to convert string to number (float) in Perl

How to convert string to number in Perl

$str = '10.0500000'; $number = $str * 1; # 10.05 

Is there any other standard way to get 10.05 with '10 .0500000 'instead of multiplying it by one?

+6
source share
4 answers

I answer a literal question. Perhaps you want to format the number for display.

Both expressions

 sprintf '%.2f', '10.0500000' sprintf '%.2f', 10.0500000 

returns the string 10.05 .

+13
source

Perl does not print scalars. Instead, operators. Therefore, when you execute $a . "1" $a . "1" , you use $a as a string, and when you do $a + 1 , you use $a as a number. Perl will do its best to figure out what a scalar means for a given operation. Therefore, for most cases, the "conversion" is performed implicitly for you.

If you need to verify that your string can indeed be converted, use regular expressions.

Here is one discourse on how to do this: http://www.regular-expressions.info/floatingpoint.html

+8
source

Well, you can also add 0 :-)

You should not worry about the inner representation of the scalar in perl, unless you are doing some weird things (and please tell us if you are). All that looks like a number is a number.

Or do you need to check if the string is a "real" number? Well, actually, any line. There's a good article on this topic: http://www.perl.com/doc/FMTEYEWTK/is_numeric.html

+6
source

0+ bit more idiomatic. It is commonly used to highlight the components of double characters.

 $ perl -E' system({ "nonexistant" } "nonexistant"); say 0+$!, ": ", $!; ' 2: No such file or directory 

It looks weird because it is not what you usually need to do. A number is a number, regardless of whether it is stored as PV, IV, UV, or NV. Forcing it to save as NV (float) should not be necessary, and it usually indicates an erroneous design elsewhere.

+2
source

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


All Articles