環境
Unity 2019.3.7f1
はじめに
私がよく使う型変換
・string→int
・string→float
・float→int
・int→桁数指定してstring
をまとめました。(覚えられない)
方法
・string→int
int型の変数 = int.Parse("数字の文字")
・string→float
float型の変数 = float.Parse("数字の文字")
・float→int
float→intに関しては2種類あります。
-(int)を使う-
int型の変数 = (int)数値
小数点以下は切り捨てになります。
-Mathfを使用した変換-
切り上げ: int型の変数 = Mathf.CeilToInt(数値);
切捨て : int型の変数 = Mathf.FloorToInt(数値);
四捨五入: int型の変数 = Mathf.RoundToInt(数値);
RoundToIntに関して、
小数点が5の場合、偶数に近い方に変換されるため注意!
・int→桁数指定してstring
string型の変数 = 数値.ToString("000")
0の数で桁数が決まります。
具体例
・string→int
文字列の100をint型に変換後、計算できるか確認するため1を足してます。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour
{
private int a;//int型の変数aを宣言
void Start()
{
a = int.Parse("100");//文字列100を数値に変換し変数aに代入
a = a + 1;//変数aに1を足してみる
Debug.Log("a="+a);//コンソールに表示
}
}
・string→float
文字列の1.111をfloat型に変換後、計算できるか確認するため1を足しています。
変換する文字列に「f」はつけないことに注意!!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour
{
private float a;//float型の変数aを宣言
void Start()
{
a = float.Parse("1.111");//文字列1.111を数値に変換し変数aに代入
a = a + 0.1f;//変数aに0.1を足してみる
Debug.Log("a="+a);//コンソールに表示
}
}
・float→int
-(int)を使う-
1.9999をint型に変換します。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour
{
private int a;//int型の変数aを宣言
void Start()
{
a = (int)1.9999f;//1.9999をint型に変換し変数aに代入
Debug.Log("a="+a);//コンソールに表示
}
}
-Mathfを使用した変換-
切り捨て、切り上げ、四捨五入がありますが、
代表して一番ややこしい四捨五入を行います。
なにがややこしいかというと、小数点が0.5の時、偶数に近いほうに変換されます。
これはもう"四捨五入ではないなにか"です。
1.1、1.5, 1.9、2.1, 2.5, 2.9で処理してみましょう。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour
{
private int a;//int型の変数aを宣言
private int b;//int型の変数bを宣言
private int c;//int型の変数cを宣言
private int d;//int型の変数dを宣言
private int e;//int型の変数eを宣言
private int f;//int型の変数fを宣言
void Start()
{
a = Mathf.RoundToInt(1.1f);//1.1を四捨五入しint型に変換
b = Mathf.RoundToInt(1.5f);//1.5を四捨五入しint型に変換
c = Mathf.RoundToInt(1.9f);//1.9を四捨五入しint型に変換
d = Mathf.RoundToInt(2.1f);//2.1を四捨五入しint型に変換
e = Mathf.RoundToInt(2.5f);//2.5を四捨五入しint型に変換 計算結果注意
f = Mathf.RoundToInt(2.9f);//2.9を四捨五入しint型に変換
Debug.Log("a=" + a);//コンソールに表示
Debug.Log("b=" + b);//コンソールに表示
Debug.Log("c=" + c);//コンソールに表示
Debug.Log("d=" + d);//コンソールに表示
Debug.Log("e=" + e);//コンソールに表示
Debug.Log("f=" + f);//コンソールに表示
}
}
2.5の処理結果e=をみると2となっています。
このように私たちの感覚では2.5を四捨五入すると3になりますが、
偶数に近い側の2に変換されてしまいます。
・int→桁数指定してstring
10を三桁の文字列に変換します。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test4 : MonoBehaviour
{
private string a;//string型の変数aを宣言
void Start()
{
a = 10.ToString("000");//数値を桁数指定で文字列に変換
Debug.Log("a=" + a);//コンソールに表示
}
}
おわりに
・文字列から数値はParse
・floatからintはMathfを確認
・数値から桁数指定はToString
くらいの感じで覚えておけばすぐ対応できそうですね。