Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java float 123.129456 to 123.12 without rounding

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

123.99999 to 123.99
-8.022222 to -8.02

There should be no rounding just cut of the decimal places and leave two.

Second point is how do you validate or count how many decimals are after the point?:

123.99 will give true or 2
123.999 will give false or 3

UPDATE

The numbers are String input so I think I will go with this as suggested; and I'll just have int try/catch block for any exceptions. Any suggestions how to make this work any smarter way are welcome:

public static float onlyTwoDecimalPlaces(String number) {
    StringBuilder sbFloat = new StringBuilder(number);
    int start = sbFloat.indexOf(".");
    if (start < 0) {
        return new Float(sbFloat.toString());
    }
    int end = start+3;
    if((end)>(sbFloat.length()-1)) end = sbFloat.length();

    String twoPlaces = sbFloat.substring(start, end);
    sbFloat.replace(start, sbFloat.length(), twoPlaces);
    return new Float(sbFloat.toString());
}
like image 201
MatBanik Avatar asked Feb 19 '11 14:02

MatBanik


1 Answers

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.

like image 150
Udi Reshef Avatar answered Oct 06 '22 02:10

Udi Reshef