6

Don’t use floats and doubles in Java to represent Money values (or anything wher...

 1 year ago
source link: https://www.kevinhooke.com/2023/07/27/dont-use-floats-and-doubles-in-java-to-represent-money-values-or-anything-where-you-need-exact-values/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Don’t use floats and doubles in Java to represent Money values (or anything where you need exact values)

Float and double types in Java are approximations – they don’t represent exact values. This is by design to allow faster calculations of approximate values at the cost of exact accuracy.

If you are new to Java, at some point you will run into this, or you’ll come across someone else you work with who may tell you to never use floats and doubles to represent Money, but maybe you’re not sure why. The reason is because of how floats and doubles represent approximate values.

If you’ve never come across this before, try this experiment:

float result = 0.01f + 0.01f + 0.01f;

You would expect this calculation to represent 0.03, but if you compare the value of result with 0.03f you’ll find this snippet of code unexpectedly prints false:

if(result == 0.03f){
    System.out.println("true");
}
else{
    System.out.println("false");
}

To represent accurate floating point values use BigDecimal. Alternatively, money values can be represented as an integer value in cents or pennies (for example) to avoid the approximation issues.

tldr; Don’t use floats and doubles to represent money values in Java.

CategoriesKev's BlogTagsbest practices, floating point, java, money

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Comment *

Name *

Email *

Website

Save my name, email, and website in this browser for the next time I comment.

Notify me of follow-up comments by email.

Notify me of new posts by email.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Post navigation


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK