Java float 123.129456 to 123.12 without rounding

后端 未结 5 2093
一个人的身影
一个人的身影 2020-12-20 16:11

How do you cut down float primitive in java to two decimal places, without using rounding?:

123.99999 to 123.99
-8.022222 to         


        
5条回答
  •  Happy的楠姐
    2020-12-20 16:38

    When you use DecimalFormat be aware to the fact that many languages uses "," instead of "." for float. So while you will format your float to "0.00" it will become "0,00" in certain locales (such as German and Polish). This will cause a NullPointerException while you will use this new formatted float in android applications. So what I did in order to cut and not round is to cast it to int after multiply it with 100 then recast it back to float and divide it to 100 This is the line:

    myFloat = (float)((int)( myFloat *100f))/100f;
    

    You can try it with log:

    float myFloat = 12.349;
    myFloat = (float)((int)( myFloat *100f ))/100f;
    Log.d(TAG, " myFloat = "+ myFloat);       //you will get myFloat = 12.34
    

    This will cut myFloat two places after the decimal point to format of ("0.00") it will not round it like this line (myFloat = Math.round(myFloat *100.0)/100.0;) it will just cut it.

提交回复
热议问题