简体   繁体   English

对于 Java 中的大数,double 与 long

[英]double versus long for large numbers in Java

I'm just starting to learn to code and this might be a very simple question but I have seen double used for numbers that are larger than int can hold.我刚刚开始学习编码,这可能是一个非常简单的问题,但我已经看到 double 用于大于 int 可以容纳的数字。 If I understand correctly, double is less precise than using long might be.如果我理解正确, double 可能不如使用 long 精确。

So if I have a number larger than int can hold, would it be best to use double or long?因此,如果我的数字大于 int 可以容纳的数字,最好使用 double 还是 long? In what cases is one preferred over the other?在什么情况下一种优于另一种? What is best practice for this?对此的最佳做法是什么?

(Say I would like to store a variable with Earth's population. Is double or long preferred?) (假设我想用地球人口存储一个变量。是 double 还是 long 首选?)

tl;dr tl;博士

For population of humans, use long primitive or Long class.对于人类群体,使用long原始或Long class。

Details细节

The floating-point types trade away accuracy in exchange for speed of execution.浮点类型以牺牲精度来换取执行速度。 These types in Java include float / Float and double / Double . Java 中的这些类型包括float / Floatdouble / Double

If working with whole numbers (no fractions):如果使用整数(无分数):

  • For smaller numbers ranging from -2^31 to 2^31-1 (roughly plus or minus 2 billion, use int / Integer . Needs 32-bits for content.对于从 -2^31 到 2^31-1 的较小数字(大约正负 20 亿,请使用int / Integer 。内容需要 32 位。
  • For larger numbers, use long / Long .对于较大的数字,请使用long / Long Needs 64-bits for content.内容需要 64 位。
  • For extremely large numbers, use BigInteger .对于非常大的数字,请使用BigInteger

If working with fractional numbers (not integers):如果使用小数(不是整数):

  • For numbers between (2-2^-23) * 2^127 and 2^-149 where you do not care about accuracy, use float / Float .对于 (2-2^-23) * 2^127 和 2^-149 之间的数字,您关心准确性,请使用float / Float Needs 32-bits for content.内容需要 32 位。
  • For larger/smaller numbers where you do not care about accuracy, use double / Double .对于您关心准确性的较大/较小数字,请使用double / Double Needs 64-bits for content.内容需要 64 位。
  • For more extreme numbers, use BigDecimal .对于更极端的数字,请使用BigDecimal
  • If you care about accuracy (such as money matters), use BigDecimal .如果您关心准确性(例如金钱问题),请使用BigDecimal

So for the earth's population of humans, use long / Long .所以对于地球上的人口,使用long / Long

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM