Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

floating point - 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());
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...