#!/usr/bin/perl -wl use strict; ####################### ## string numerifier ## ####################### # SI prefix to exponent value conversion table my %SI = ( Y => +24, # yotta Z => +21, # zetta E => +18, # exa P => +15, # peta T => +12, # terra G => +9, # giga M => +6, # mega k => +3, # kilo K => +3, # kilo "" => 0, # default is no SI prefix m => -3, # milli u => -6, # micro n => -9, # nano p => -12, # pico f => -15, # femto a => -18, # atto z => -21, # zepto y => -24, # yocto ); sub num { my ($numstr) = @_; # string must contain digit if ($numstr =~ /\d/) { # clean string for best chance at numerification my ($sign, $exponent, $siprefix) = ("+", 0, ""); if ($numstr =~ /^[^.]*\d/) # does first digit appear before po +tential decimal point? { $numstr =~ s/^.*?([+-]?)(\d+[.]?\d*)(?:[eE]([+-]?\d+))?([Y +ZEPTGMkKmunpfazy])?.*/$2/; $sign = $1 if $1; $exponent = $3 if $3; $siprefix = $4 if $4; } else { $numstr =~ s/^.*?([+-]?)(\d*[.]?\d+)(?:[eE]([+-]?\d+))?([Y +ZEPTGMkKmunpfazy])?.*/$2/; $sign = $1 if $1; $exponent = $3 if $3; $siprefix = $4 if $4; } # convert SI prefixes -- example: ".16E2m" => ".16e-1" => 0.01 +6 if ($exponent || $siprefix) { $exponent += $SI{$siprefix}; $numstr .= "e".$exponent; } # numerify string according to nearest sign { no warnings 'numeric'; $numstr = -+-$numstr; # high-precedence nu +merifier $numstr = -$numstr if $sign eq "-"; # negative if last s +ign is "-" } } else { $numstr = undef; } return($numstr); } ############## # test cases # ############## print "|".num("+-- 123.mA")."|"; # output: "|0.123|" print "|".num(" -+--.15e4u99..99.0")."|"; # output: "|-0.0015|" print "|".num(" -+-- 789. G5e2")."|"; # output: "|789|" print "|".(1e-6 == num("1e-6"))."|"; # output: "|1|" print "|".(1e-6 == num("1e3n"))."|"; # output: "|1|" print "|".(1e-6)."|".(1e3*1e-9)."|"; # output: "|1e-06|1e-06|" print "|".(1e-6 == 1e3*1e-9)."|"; # output: "||" -- low-level FP l +imitation, perhaps with C's strtod()
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: String numerifier with SI prefix support
by toolic (Bishop) on Feb 01, 2008 at 01:18 UTC | |
by repellent (Priest) on Feb 01, 2008 at 02:18 UTC | |
by toolic (Bishop) on Feb 01, 2008 at 14:06 UTC |