You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中将字符串"-0"解析为double-0.0及指定long值?

问题1:如何在C#中将字符串"-0"解析为double类型的-0.0?

默认情况下,double.Parse("-0")会返回正0.0,因为.NET的数值解析器会把带负号的零视为常规零。要得到二进制表示为0x8000000000000000的负零,你需要手动处理:

string input = "-0";
double negativeZero = double.Parse(input);
// 检查原字符串包含负号且解析结果为0,手动设置为负零
if (input.StartsWith("-") && negativeZero == 0.0)
{
    negativeZero = -0.0;
}

或者用更简洁的方式直接生成负零:

double negativeZero = -Math.Abs(double.Parse("-0"));

验证二进制表示的话,可以用这段代码:

long bits = BitConverter.DoubleToInt64Bits(negativeZero);
Console.WriteLine(bits.ToString("X")); // 输出 8000000000000000
问题2:如何在C#中将字符串"-0"解析为long类型值-9223372036854775808(十六进制:0x8000000000000000)?

这个long值本质是double负零的二进制表示,不能直接把字符串"-0"解析为long(直接解析会得到0)。正确的步骤是:

  1. 先把"-0"处理为double类型的负零
  2. 用BitConverter.DoubleToInt64Bits将其转换为对应的long值

示例代码如下:

string input = "-0";
double negativeZeroDouble = double.Parse(input);
// 确保得到负零
if (input.StartsWith("-") && negativeZeroDouble == 0.0)
{
    negativeZeroDouble = -0.0;
}
long negativeZeroLong = BitConverter.DoubleToInt64Bits(negativeZeroDouble);
Console.WriteLine(negativeZeroLong); // 输出 -9223372036854775808
Console.WriteLine(negativeZeroLong.ToString("X")); // 输出 8000000000000000
为什么你的示例代码中两个值不相等?

你代码里的这一行:

long parsedNegativeZeroLong = BitConverter.DoubleToInt64Bits(System.Double.Parse("-0.0", System.Globalization.NumberStyles.Float));

Double.Parse("-0.0")返回的是正0.0——因为解析器会自动忽略负号后面的零,所以转换后的long值是0;而你手动定义的-0.0的二进制表示是0x8000000000000000,两者自然不相等。

内容的提问来源于stack exchange,提问作者TomaC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:12:56