9cubed
ブログ | Tailwind | Vite | Python | Node.js | Linux | PowerShell | その他 | 将棋ウォーズ | 歌の練習
< 前の記事

Kotlin - Hello, world!

次の記事 >

Kotlin - 型のチェック

Kotlin

Kotlin - 文字列と数値の変換

公開日:2019-11-06
更新日:2019-11-06

1. 概要

文字列と数値の相互変換を行います。


2. 文字列を数値に変換

var n1:Int = "-00123".toInt()
var n2:Int = Integer.parseInt("-00123")
var n3:Int = Integer.valueOf("-00123")

println(n1) // -123
println(n2) // -123
println(n3) // -123

数値に変換できない場合は、NumberFormatException が発生します。
var n1:Int = "abc".toInt()           // java.lang.NumberFormatException: For input string: "abc"
var n2:Int = Integer.parseInt("abc") // java.lang.NumberFormatException: For input string: "abc"
var n3:Int = Integer.valueOf("abc")  // java.lang.NumberFormatException: For input string: "abc"

println(n1) // -123
println(n2) // -123
println(n3) // -123

数値変換時の例外を発生させないようにするには、toIntOrNull() などの OrNull がついたメソッドを使用します。
変換できない場合は null が返るため、受け取る変数は Null許容型にする必要があります。
var n1:Int? = "abc".toIntOrNull()

println(n1) // null


3. 数値を文字列に変換

var s:String = (-123).toString()

println(s) // -123

< 前の記事

Kotlin - Hello, world!

次の記事 >

Kotlin - 型のチェック

YouTube X

新着一覧

  • SCSS のインストールVite
  • Tailwind CSS のプロジェクトの作成Tailwind
  • TypeScriptのプロジェクトの作成Vite
  • Flask のインストールと動作確認Python
  • 簡易Webサーバーの作成Python
  • pipeline で文章の生成Python
  • pipeline で文章の要約Python
  • 音声から文字起こしPython
  • Node.js のインストールNode.js
  • .ps1(PowerShellスクリプト)を実行可能にするPowerShell

アーカイブ

  • 2025/12
  • 2025/11
  • 2025/10
  • 2025/09
  • 2025/08

以前のカテゴリー一覧

  • CakePHP3
  • CentOS7
  • HTML・CSS・JavaScript
  • Haskell
  • JavaScript
  • Kotlin
  • Laravel5
  • PHP
  • Python
  • Ruby
  • RubyOnRails5
  • TypeScript
  • Vue.js
  • Webサーバ講座
  • Webプログラミング講座
  • jQuery
  • linux
  • パソコン講座
  • ブログ
  • プログラミング講座
  • メモ帳作成講座
  • 数学

Copyright © 9cubed. All Rights Reserved.

プライバシーポリシー 利用規約
▲