Java float 123.129456 to 123.12 without rounding

后端 未结 5 2074
一个人的身影
一个人的身影 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条回答
  • 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.

    0 讨论(0)
  • 2020-12-20 16:43

    Do keep in mind that float are floating point values. So there might not even be an exact two decimal representation for a certain number.

    Having said that, you might try something like:

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

    You might need to use a different RoundingMode though. Depends on what you want.

    0 讨论(0)
  • 2020-12-20 16:50

    The easy way to use DecimalFormat:

    DecimalFormat df = new DecimalFormat("0.00");
    float f = -8.0222222f;
    f = Float.parseFloat(df.format(f));
    System.out.println(f);
    
    0 讨论(0)
  • 2020-12-20 16:58

    Please try this, this one works for you.

    double d = 16.66667;
    DecimalFormat decimalFormat= new DecimalFormat("#.##");
    decimalFormat.setRoundingMode(RoundingMode.FLOOR);
    System.out.println("Result :"+decimalFormat.format(d));
    
    0 讨论(0)
  • 2020-12-20 16:59

    First of all, there is no guarantee that just because a float can represent a.bcde exactly, it is guaranteed to be able to represent a.bc exactly.

    So if you're after just the printing part, how about doing it with some string-manipulation? Find the decimal point using indexOf and extract the part with two decimals, using substring.

    0 讨论(0)
提交回复
热议问题