如何决定使用什么

编程入门 行业动态 更新时间:2024-10-24 22:21:43
本文介绍了如何决定使用什么-双精度还是十进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: 十进制与双精度!-我应该使用哪个?何时使用?

我在交易软件中使用的是 double 类型的价格.我注意到有时会出现一些奇怪的错误.如果价格在点"之后包含4位数字(例如2.1234),则会发生这种情况.

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.

当我从程序"2.1234"发送来的市价单显示为"2.1235".

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

我不使用十进制,因为我不需要极端"精度.我不需要将示例"2.00000000003"与"2.00000000002"区分开.我需要一个小数点后最多6位数字.

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?

我应该对任何金融操作使用 decimal 吗?即使我只需要一个点后一位数字?(1.1 1.2等)

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

我知道 decimal 相当慢,因此除非绝对需要 decimal ,否则我宁愿使用 double .

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

推荐答案

在处理要(并且可以)以10为基数表示的数量时,请使用小数.这包括货币值,因为您希望将2.1234精确表示为2.1234.

Use decimal whenever you're dealing with quantities that you want to (and can) be represented exactly in base-10. That includes monetary values, because you want 2.1234 to be represented exactly as 2.1234.

当您不需要以10为基数的精确表示形式时,请使用double.通常,这对于处理测量值很有好处,因为这些已经是近似值,而不是精确的数量.

Use double when you don't need an exact representation in base-10. This is usually good for handling measurements, because those are already approximations, not exact quantities.

当然,如果对您而言,以10为基数的确切表示形式对您而言并不重要,则可以考虑其他因素,具体取决于具体情况,这些因素可能无关紧要:

Of course, if having or not an exact representation in base-10 is not important to you, other factors come into consideration, which may or may not matter depending on the specific situation:

  • double的范围更大(它可以处理非常大和非常小的幅度);
  • 十进制具有更高的精度(具有更多有效数字);
  • 您可能需要使用double来与一些不知道小数的旧API进行交互;
  • double快于十进制;
  • 十进制具有更大的内存占用;

更多推荐

如何决定使用什么

本文发布于:2023-11-24 19:56:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626603.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!