Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse from String and convert to float, integer (Raku)

Tags:

raku

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)
like image 904
Tinmarino Avatar asked Mar 25 '20 16:03

Tinmarino


2 Answers

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)
  • Info

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

  • Same question in Python, Perl
  • Roseta Code: Determine if a string is numeric

Edited thanks to @Holli comment

like image 138
Tinmarino Avatar answered Nov 15 '22 08:11

Tinmarino


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;
    #...
}
like image 20
p6steve Avatar answered Nov 15 '22 08:11

p6steve