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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…