1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Unity】任意の小数点以下の桁で四捨五入を実装しよう

Last updated at Posted at 2024-08-12

ゲームのスコアを四捨五入して表示したいけど、Unityに四捨五入できる関数がないらしいので自分で作ろう!

参考文献

こちらの記事を参考に、好きな小数点以下の値で四捨五入できるようにした。

コード

//num 四捨五入する数字 DecPoint 四捨五入する位
public float Rounding(float num,float DecPoint)
    {
        float rounded;//ここに四捨五入した後の値を代入する
        float DecPart=num-Mathf.FloorToInt(num);//小数部分を取り出す
        int Dec1 =Mathf.FloorToInt(DecPart*Mathf.Pow(10,DecPoint));//小数部分10倍→小数点第二位以下切り捨て
        int Dec2=Dec1-Mathf.FloorToInt(Dec1/10)*10;//四捨五入する値以上の数字を消す
        //四捨五入のけいさん
        if(Dec2>=5)
        {
            rounded=Mathf.CeilToInt(num*Mathf.Pow(10,DecPoint-1));
            rounded/=Mathf.Pow(10,DecPoint-1);
        }
        else
        {
            rounded=Mathf.FloorToInt(num*Mathf.Pow(10,DecPoint-1));
            rounded/=Mathf.Pow(10,DecPoint-1);
        }
        return rounded;
    }

コードの解説

人間が頭で考えるのと同じように、

  1. 四捨五入する値を探す
  2. 値が5以上か判定する
  3. 切り上げor切り捨てする

という風に進めていく。

あると嬉しい前提知識

・Mathf.FloorToInt() 小数点以下切り捨て
・Mathf.CeilToInt() 小数点以下切り上げ
・Mathf.Pow(a,b) aのb乗
・中学数学の基礎知識(循環小数→分数あたりがわかっていると楽かもしれない)

1.四捨五入する値を探す

ここでは「2. 値が5以上か判定する」のために値を探して取り出すことが目標。
まずは小数部分だけを取り出す。

        float DecPart=num-Mathf.FloorToInt(num);//小数部分を取り出す

(四捨五入する数字)-(整数部分)で小数部分だけにする。
(整数部分は Mathf.FloorToInt(num) で小数部分を切り捨てて求める。)

小数部分が求まったら、四捨五入する数字だけを取り出す。

        int Dec1 =Mathf.FloorToInt(DecPart*Mathf.Pow(10,DecPoint));//小数部分10倍→小数点第二位以下切り捨て

小数点移動して、四捨五入する値が一の位になったら、
小数部分は使わないので Mathf.FloorToInt で切り捨て。

最後に判定のために一の位だけにする。

        int Dec2=Dec1-Mathf.FloorToInt(Dec1/10)*10;

十の位以上の数字をなくすために、小数点移動→整数部分切り捨て→小数点戻す。

2. 値が5以上か判定する

先ほど取り出したDec2をifを使って判定。(ただのif文なので割愛。)

3. 切り上げor切り捨てする

まずは切り上げから

            rounded=Mathf.CeilToInt(num*Mathf.Pow(10,DecPoint-1));
            rounded/=Mathf.Pow(10,DecPoint-1);

num * Mathf.Pow(10,DecPoint-1)で切り上げたい位まで小数点を移動させて切り上げ。
そのあと小数点を戻す。

切り下げの場合も同様。

            rounded=Mathf.FloorToInt(num*Mathf.Pow(10,DecPoint-1));
            rounded/=Mathf.Pow(10,DecPoint-1);
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?