Rik Johnson
Rik Johnson

Reputation: 111

How to a parse a string into a float with three decimal points in java

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.

Upvotes: 2

Views: 1163

Answers (2)

Gooz
Gooz

Reputation: 1136

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

Upvotes: 1

corsiKa
corsiKa

Reputation: 82589

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.

Upvotes: 1

Related Questions