如何将double转换为long而不截断它?
例如,
我希望-26.3999745成为-263999745
到目前为止,我尝试过的方法如Convert.ToInt64()
截断了数字。
编辑: 小数位数会有所不同,有些数字可能有5个小数位
答案 0 :(得分:3)
如果你确定这是你真正想要的......
long.Parse((-26.3999745).ToString().Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.ToString(), string.Empty)))
答案 1 :(得分:3)
遵循两个步骤
n
10^n
代码:
double number = -26.3999745;
int n = BitConverter.GetBytes(decimal.GetBits((decimal)number)[3])[2];
long result = (long)(number * Math.Pow(10, n));
如果您想遵循单一责任(您应该),那么您可以使用第二种方法,这种方法也不是特定于文化的:
static int GetCountAfterDecimal(double number)
{
int count = 0;
string seperator = System.Globalization.CultureInfo.CurrentCulture
.NumberFormat.NumberDecimalSeparator;
string numberAsString = number.ToString();
int indexOfSeperator = numberAsString.IndexOf(seperator);
if (indexOfSeperator >= 0)
count = numberAsString.Length - indexOfSeperator - 1;
return count;
}
static long RemoveDecimalPoint(double number, int numbersCountAfterDecimal)
{
return (long)(number * Math.Pow(10, numbersCountAfterDecimal));
}
static void Main(string[] args)
{
double number = -26.3999745;
long result = RemoveDecimalPoint(number, GetCountAfterDecimal(number));
Console.WriteLine(result);
}
答案 2 :(得分:0)
这可能会为你做到这一点
double YourNumber = -26.3999745;
int DecimalPlacesCount = BitConverter.GetBytes(decimal.GetBits(Convert.ToDecimal(YourNumber))[3])[2];
long number = Convert.ToInt64("1".PadRight(DecimalPlacesCount + 1, '0'));
long kajs = (long) (YourNumber * number);