Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string number to a real number?

Tags:

regex

perl

I was wondering if there is a way to convert a number like

100u     10km     300nm      and so on

so that they are interpreted as:

100*10^-6      10*10^3      300*10^-6

I need to compare these numbers (100u, 10km, etc.). For example, if I want to compare 100u to 10u, that's ok; I just do the following, which is not correct but does the job:

$distance =~ s/(.*)u/$1/;
if ($distance >= $desired_distance) {
       printf $distance;
}

where (.*)u is the number, e.g. 100u. So I just remove the u and then compare it with a number.

But, what if I have the number

1.45m 

and I want to compare it with

1400u

The above thing wouldn't help.

like image 752
TheBlackCorsair Avatar asked Nov 28 '22 02:11

TheBlackCorsair


1 Answers

Number::FormatEng will help to convert standard prefixes into numeric values:

use warnings;
use strict;

use Number::FormatEng qw(:all);
for (qw(100u 1.45m 1400u)) {
    print "$_ ", unformat_pref($_), "\n";
}

__END__

100u 0.0001
1.45m 0.00145
1400u 0.0014
like image 93
toolic Avatar answered Dec 18 '22 23:12

toolic