[英]Int64 as result from double times 10^x?
I have a variable representing a quantity in some given unit: 我有一个以给定单位表示数量的变量:
enum Unit
{
Single,
Thousand,
Million,
Billion,
Trillion
}
public class Quantity()
{
public double number;
public Unit numberUnit;
public Int64 GetNumberInSingleUnits()
{
// ???
}
}
For example, imagine 例如,想象
var GDP_Of_America = new Quantiy { number = 16.66, numberUnit = Unit.Trillion };
Int64 gdp = GDP_Of_America.GetNumberinSingleUnits(); // should return 16,660,000,000,000
My question is basically - how can I implement the "GetNumberInSingleUnits" function? 我的问题基本上是-如何实现“ GetNumberInSingleUnits”功能? I can't just multiply with some UInt64 factor, eg
我不能只用一些UInt64因素相乘,例如
double num = 0.5;
UInt64 factor = 1000000000000;
var result = num * factor; // won't work! results in double
As the regular numeric operations reslt in a double, but the result may be larger than the range of valid doubles. 由于常规数值运算会重整为double型,但结果可能大于有效double型的范围。
How could I do this conversion? 我该如何进行转换?
ps, I know the class "Quantity" is not a great way to store information - but this is bound by the input data of my application, which is in non-single (eg millions, billions etc) units. ps,我知道“数量”类并不是存储信息的好方法-但这受我的应用程序的输入数据限制,该输入数据的单位不是单个(例如,数百万,数十亿等)。
Like I said, decimal
s can help you here: 就像我说的,
decimal
可以在这里为您提供帮助:
public enum Unit
{
Micro = -6, Milli = -3, Centi = -2, Deci = -1,
One /* Don't really like this name */, Deca, Hecto, Kilo, Mega = 6, Giga = 9
}
public struct Quantity
{
public decimal Value { get; private set; }
public Unit Unit { get; private set; }
public Quantity(decimal value, Unit unit) :
this()
{
Value = value;
Unit = unit;
}
public decimal OneValue /* This one either */
{
get
{
return Value * (decimal)Math.Pow(10, (int)Unit);
}
}
}
With decimal
s you won't lose a lot of precision until after you decide to convert them to long
(and beware of over/underflows). 使用
decimal
s之前,除非您决定将它们转换为long
(并注意上溢/下溢),否则您不会损失很多精度。
Anton's answer seems like a good solution. 安东的答案似乎是一个很好的解决方案。 Just for the sake of discussion, another potential way.
只是为了讨论,另一种可能的方式。
I don't like this one at all as it seems very messy; 我一点都不喜欢这个,因为看起来很乱。 However I think this might avoid imprecisions, if these ever turned out to be an issue with decimals.
不过,我认为这可能避免不精确,如果这些曾经竟然是带有小数的问题。
public Int64 GetAsInt64(double number)
{
// Returns 1 for single units, 3 for thousands, 6 for millions, etc.
uint e = GetFactorExponent();
// Converts to scientific notation
// e.g. number = -1.2345, unit millions to "-1.2345e6"
string str = String.Format("{0:#,0.###########################}", number) + "e" + e;
// Parses scientific notation into Int64
Int64 result = Int64.Parse(str, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent | NumberStyles.AllowThousands);
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.