从字符串解析并转换为浮点数、整数 (Raku)

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

常见问题解答:在 Raku 中,我如何解析 String and get a Number ?例如:

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)

只需使用 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 正在做你(我)想要的。

注意它正在返回 Allomorph object. Use unival or just + prefix to convert it to Number

  • 链接:

  • Learning Raku:数字、字符串和 NumberString 同质变体

  • Python, Perl
  • 中的相同问题
  • Roseta Code:判断字符串是否为数字

编辑感谢@Holli 评论

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* ( .* )// ) {
    my $factor = [=10=];
    #...
}