1

I am trying the below code but after executing 344741.79 value is showing as 344741.78

Means after decimal place .79 is getting converted to .78, I am really wondering why I am not getting the exactly same value after conversion and which logic is doing this?

public static void main(String[] s) {
 double a = 344741.79;
 System.out.print(new Float(a));
}
aUserHimself
1,5972 gold badges18 silver badges27 bronze badges
asked Mar 17, 2017 at 6:35
3
  • 4
    You lose some precision when converting from a double to a float in Java. Commented Mar 17, 2017 at 6:36
  • 2
    And while that may or may not be the case here, you also lose precision during compilation when converting from that Java source code literal to double (which cannot represent all decimal fractions either). Commented Mar 17, 2017 at 6:37
  • 1
    You should use the BigDecimal class if you require precision Commented Mar 17, 2017 at 6:50

1 Answer 1

1

Float is only guaranteed to accurately store 6 significant decimal digits. In the case of 344741.79, the 2 nearest Floats are 344741.78125 (which is printed as 344741.78) and 344741.8125 (which is printed as 344741.8).

answered Mar 17, 2017 at 8:41
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer and time :)
If you're happy with the answer, please accept it by clicking the tick.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.