How to decide what to use - double or decimal? [du

2020-05-25 07:14发布

Possible Duplicate:
decimal vs double! - Which one should I use and when?

I'm using double type for price in my trading software. I've noticed that sometimes there are a odd errors. They occur if price contains 4 digits after "dot", like 2.1234.

When I sent from my program "2.1234" on the market order appears at the price of "2.1235".

I don't use decimal because I don't need "extreme" precision. I don't need to distinguish for examle "2.00000000003" from "2.00000000002". I need maximum 6 digits after a dot.

The question is - where is the line? When to use decimal?

Should I use decimal for any finansical operations? Even if I need just one digit after the dot? (1.1 1.2 etc.)

I know decimal is pretty slow so I would prefer to use double unless decimal is absolutely required.

标签: c# .net
11条回答
闹够了就滚
2楼-- · 2020-05-25 07:39

For financial operation I always use the decimal type

查看更多
做自己的国王
3楼-- · 2020-05-25 07:41

If you always know the maximum amount of decimals you are going to have (digits after the point). Then the best practice is to use fixed point notation. That will give you an exact result while still working very fast.

The simplest manner in which to use fixed point is to simply store the number in an int of thousand parts. For example if the price always have 2 decimals you would be saving the amount of cents ($12.45 is stored in an int with value 1245 which thus would represent 1245 cents). With four decimals you would be storing pieces of ten-thousands (12.3456 would be stored in an int with value 123456 representing 123456 ten-thousandths) etc etc.

The disadvantage of this is that you would sometimes need a conversion if for example you are multiplying two values together (0.1 * 0.1 = 0.01 while 1 * 1 = 1, the unit has changed from tenths to hundredths). And if you are going to use some other mathematical functions you also has to take things like this into consideration.

On the other hand if the amount of decimals vary a lot using fixed point is a bad idea. And if high-precision floating point calculations are needed the decimal datatype was constructed for exactly that purpose.

查看更多
甜甜的少女心
4楼-- · 2020-05-25 07:44

Use decimal it's built for representing powers of 10 well (i.e. prices).

查看更多
戒情不戒烟
5楼-- · 2020-05-25 07:44

Double is meant as a generic floating-point data type, decimal is specifically meant for money and financial domains. Even though double usually works just fine decimal might prevent problems in some cases (e.g. rounding errors when you get to values in the billions)

查看更多
SAY GOODBYE
6楼-- · 2020-05-25 07:46

Decimal is the way to go when dealing with prices.

查看更多
登录 后发表回答