Java float 123.129456 to 123.12 without rounding

How do you shorten a 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 out the decimal places and leave two.

Secondly, how do you check or count how many decimal places after the dot ?:

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

UPDATE

Numbers are string inputs, so I think I will go with this as suggested; and I will just have int try / catch block for any exceptions. Any suggestions on how to make this work in a more reasonable 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());
}
+5
source share
5 answers

, , , float a.bcde, a.bc.

, , , ? indexOf , substring.

+4

DecimalFormat, , "," ".". . , float "0.00", "0,00" (, ). NullPointerException, float Android. , , int 100, , 100 :

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

:

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

myFloat ( "0.00" ) , (myFloat = Math.round(myFloat *100.0)/100.0;), .

+8

, float - . , .

, - :

float f = -8.022222f;
BigDecimal bd = new BigDecimal(f);
BigDecimal res = bd.setScale(2, RoundingMode.HALF_UP);
f = res.floatValue();
System.out.println(f);

, RoundingMode. , .

+6

DecimalFormat:

DecimalFormat df = new DecimalFormat("0.00");
float f = -8.0222222f;
f = Float.parseFloat(df.format(f));
System.out.println(f);
+2

, , .

double d = 16.66667;
DecimalFormat decimalFormat= new DecimalFormat("#.##");
decimalFormat.setRoundingMode(RoundingMode.FLOOR);
System.out.println("Result :"+decimalFormat.format(d));
+1

All Articles