I know there is a way of forcing a float to have 3 decimal points, but how do I make a string representation "4.00000009" retain 3 decimal points after I turn it into a float? Float.parseFloat() rounds it to 4.0. Not using extra libraries would be ideal.
2 Answers
If you're guaranteed that the String is properly formatted, you can take a substring based on the index of the decimal.
Alternatively, you can parse it, multiply by a thousand, round it, and divide it by a thousand.
However, this is going to be bad for you in the long run. Floating point numbers don't fare so well when exact values are needed. Consider BigDecimal instead.
Comments
This utility method takes a String and turns it into a float with 3 decimals places:
public static float getFloat(String s) {
BigDecimal decimal = new BigDecimal(s);
decimal = decimal.setScale(3, RoundingMode.HALF_UP);
return decimal.floatValue();
}
1 Comment
LppEdd
BigDecimal is the answer
s = s.substring(0, s.indexOf(".") + 4)floatcan have a specific format, afloatdoesn't.