如何以全精度打印浮点数
How to print floating point numbers in full precision
如果我的值 0.3
无法用 double
或 float
准确表示,我如何打印它的 真实值 作为字符串。像 this:
这样的程序
using System;
class Program
{
static void Main(string[] args)
{
var line = Console.ReadLine();
var d = float.Parse(line);
Console.WriteLine("{0:R}", d);
}
}
with 0.3
作为输入打印 0.3
这对我来说很奇怪,因为根据 this 它应该是 0.300000011920928955078125
.
所以问题是我如何强制 .net 将 float
/double
格式化为其 真实 值。
根据Standard numeric format strings
R
recommended for the BigInteger
type only. For Double
types, use
"G17"; for Single
types, use "G9".
所以,尝试使用 G9
(因为 float
给你最多 9 位有效数字的精度),它给你一个预期的输出
Console.WriteLine("{0:G9}", d);
最后我会看到 0.300000012
值
如果我的值 0.3
无法用 double
或 float
准确表示,我如何打印它的 真实值 作为字符串。像 this:
using System;
class Program
{
static void Main(string[] args)
{
var line = Console.ReadLine();
var d = float.Parse(line);
Console.WriteLine("{0:R}", d);
}
}
with 0.3
作为输入打印 0.3
这对我来说很奇怪,因为根据 this 它应该是 0.300000011920928955078125
.
所以问题是我如何强制 .net 将 float
/double
格式化为其 真实 值。
根据Standard numeric format strings
R
recommended for theBigInteger
type only. ForDouble
types, use "G17"; forSingle
types, use "G9".
所以,尝试使用 G9
(因为 float
给你最多 9 位有效数字的精度),它给你一个预期的输出
Console.WriteLine("{0:G9}", d);
最后我会看到 0.300000012
值