Reputation: 669
For representing money I know it's best to use C#'s decimal
data type to double
or float
, however if you are working with amounts of money less than millions wouldn't int
be a better option?
Does decimal
have perfect calculation precision, i.e. it doesn't suffer from Why computers are bad at numbers? If there is still some possibility of making a calculation mistake, wouldn't it be better to use int and just display the value with a decimal separator?
Upvotes: 2
Views: 2200
Reputation: 1379
The amounts you are working with, "less than millions" in your example, isn't the issue. It's what you want to do with the values and how much precision you need for that. And treating those numbers as integers doesn't really help - that just puts the onus on you to keep track of the precision. If precision is critical then there are libraries to help; BigInteger and BigDecimal packages are available in a variety of languages, and there are libraries that place no limit on the precision Wikipedia has a list The important takeaway is to know your problem space and how much precision you need. For many things the built in precision is fine, when it's not you have other options.
Upvotes: 2
Reputation: 338
Like li223 said, integer won't allow you to save values with decimal cases - and the majority of currencies allow decimal values.
I would advise to pick a number of decimal cases to work with, and avoid the problem that you refered ("Why computers are bad at numbers"). I work with invocing and we use 8 decimal cases, and works fine with all currencies so far.
Upvotes: 1
Reputation: 369
The main reason to use decimal over integer in this case is that decimal, well, allows decimal places IE: £2.50 can be properly represented as 2.5 with a decimal. Whereas if you used an integer you can't represent decimal points. This is fine if, like John mentions in their comment, you're representing a currency like Japanese Yen that don't have decimals.
As for decimal's accuracy, it still suffers from "Why are computers bad at numbers" see the answer to this question for more info.
Upvotes: 0