文字列を数値に変換する
整数
groovy:000> new Float("10") ===> 10.0 groovy:000> Integer.decode("10") ===> 10 groovy:000> Long.decode("10") ===> 10 groovy:000> new BigInteger("10") ===> 10
浮動小数点
groovy:000> new Float("1.2") ===> 1.2 groovy:000> Integer.decode("1.2") ERROR java.lang.NumberFormatException: For input string: "1.2" at java_lang_Integer$decode.call (Unknown Source) at groovysh_evaluate.run (groovysh_evaluate:2) ... groovy:000> Long.decode("1.2") ERROR java.lang.NumberFormatException: For input string: "1.2" at java_lang_Long$decode.call (Unknown Source) at groovysh_evaluate.run (groovysh_evaluate:2) ... groovy:000> new BigInteger("1.2") ERROR java.lang.NumberFormatException: For input string: "1.2" at groovysh_evaluate.run (groovysh_evaluate:2)
16進数表現
groovy:000> new Float("0x10") ERROR java.lang.NumberFormatException: For input string: "0x10" at groovysh_evaluate.run (groovysh_evaluate:2) ... groovy:000> Integer.decode("0x10") ===> 16 groovy:000> Long.decode("0x10") ===> 16 groovy:000> new BigInteger("0x10") ERROR java.lang.NumberFormatException: For input string: "x10" at groovysh_evaluate.run (groovysh_evaluate:2)
8進数表現
groovy:000> new Float("010") ===> 10.0 groovy:000> Integer.decode("010") ===> 8 groovy:000> Long.decode("010") ===> 8 groovy:000> new BigInteger("010") ===> 10
任意の進数表現
parseIntの第2パラメータに進数表現を指定する。
- 2進数
groovy:000> Integer.parseInt("10101010101010",2) ===> 10922 groovy:000> Long.parseLong("10101010101010",2) ===> 10922
- 何進数までいけるのか?
使用可能な最大基数は36
groovy:000> Character.MAX_RADIX ===> 36
まとめ
Float | Integer | Long | BigInteger | |
整数 | ○ | ○ | ○ | ○ |
浮動小数点 | ○ | × | × | × |
16進数 | × | ○ | ○ | × |
8進数 | × | ○ | ○ | × |
n | × | parseInt(X,n)○ | parseLong(X,n) | × |
実行環境
- OS:Windows XP
- Groovy Version: 1.6.5
- JVM: 1.6.0_12