2

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.

5
  • What's the problem there exactly? 4.0 = 4.000 Commented Mar 4, 2017 at 19:07
  • s = s.substring(0, s.indexOf(".") + 4) Commented Mar 4, 2017 at 19:08
  • It's simply a requirement that I have to have 3 decimal points, regardless of the equivalence in values. Commented Mar 4, 2017 at 19:08
  • @DannyLiang Can you elaborate? As Joseph said, 4.0 = 4.000. A string representation of a float can have a specific format, a float doesn't. Commented Mar 4, 2017 at 19:09
  • substring would just turn it into another string with the correct rounding correct? I need a float Commented Mar 4, 2017 at 19:09

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

BigDecimal is the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.