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());
}
source
share