5

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)
Tinmarino
  • 3,693
  • 24
  • 33

2 Answers2

6

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

Edited thanks to @Holli comment

Tinmarino
  • 3,693
  • 24
  • 33
  • 2
    Normally you don't need `val`. You can just rely on automatic type conversion or just use the `+`. `say (+'0x42').WHAT; #Int`. – Holli Mar 25 '20 at 20:29
5
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;
    #...
}
librasteve
  • 6,832
  • 8
  • 30