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

tin*_*ino 4 raku

常见问题解答:在 Raku 中,如何解析String并获得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)
Run Code Online (Sandbox Code Playgroud)

tin*_*ino 5

只需使用前缀 +:

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)
Run Code Online (Sandbox Code Playgroud)
  • 信息

VAL一个海峡 常规做exactely你(我)想要什么。

请注意它正在返回Allomorph object。使用unival或仅+ 前缀将其转换为Number

感谢@Holli 评论编辑

  • 通常你不需要`val`。您可以仅依靠自动类型转换或仅使用“+”。`说(+'0x42')。什么;#Int`。 (2认同)

p6s*_*eve 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;
    #...
}
Run Code Online (Sandbox Code Playgroud)

  • 我使用“+”和前瞻断言的组合来测试 Real 的子字符串。 (2认同)