FAQ: In Raku, how do I parse a String and get a Number ? For example:
xxx("42"); # 42 (Int)
xxx("0x42"); # 66 (Int)
xxx("42.123456789123456789"); # 42.123456789123456789 (Rat)
xxx("42.4e2"); # 4240 (Rat)
xxx("42.4e-2"); # 0.424 (Rat)
Just use the prefix +:
say +"42"; # 42 (Int)
say +"0x42"; # 66 (Int)
say +"42.123456789123456789"; # 42.123456789123456789 (Rat)
say +"42.4e2"; # 4240 (Rat)
say +"42.4e-2"; # 0.424 (Rat)
val a Str routine is doing exactely what you (I) want.
Beware that it is returning Allomorph object. Use unival or just + prefix to convert it to Number
Links:
Learning Raku: Number, Strings, and NumberString Allomorphs
Edited thanks to @Holli comment
my regex number {
\S+ #grab chars
<?{ defined +"$/" }> #assertion that coerces via '+' to Real
}
#strip factor [leading] e.g. 9/5 * Kelvin
if ( $defn-str ~~ s/( <number>? ) \s* \*? \s* ( .* )/$1/ ) {
my $factor = $0;
#...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With