从.NET 3.5中的双精度获得精确的小数位数精度

时间:2012-02-17 11:28:16

标签: c# regex .net-3.5

由于要求,我需要非常精确的双精度值到4位小数,如下所示:

double myDoubleValue = 50234.9489898997952932;

从上面,我需要输出为50234.9489我不希望舍入此要求中的数字。

我遇到了“Math.Truncate(a * 100)/ 100;”。但实际上我对这种方法并不感兴趣。

我正在寻找更简单的方法,例如使用String.FormatRegular Expressions等。

4 个答案:

答案 0 :(得分:3)

double d = 50234.94895345345345;
var Expected_result =  Double.Parse((Regex.Match(d.ToString(), "[+-]?\\d*.\\d{0,4}")).Value);

答案 1 :(得分:2)

你需要自己做。其中一种可能的解决方案是使用扩展方法

public static class DoubleEx
{
    public static double TruncateFraction(this double value, int fractionRound)
    {
        double factor = Math.Pow(10, fractionRound);
        return Math.Truncate(value * factor) / factor;
    }
}

这是如何使用它

double foo = 50234.9489898997952932;
double bar = foo.TruncateFraction(4);

Console.WriteLine(foo); //50234.9489898997952932
Console.WriteLine(bar); //50234.9489

答案 2 :(得分:1)

没有正则表达式:

这适用于任何double组合

using System.Globalization;

class Program
{
    static void Main(string[] args)
    {
        double d = 50234.9489898997952932;
        char probablyDot = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];
        string[] number = d.ToString().Split(probablyDot);


        //Console.WriteLine(number[0] + probablyDot + number[1].Remove(4));

        Console.WriteLine(number[0] + probablyDot + (number.Length >1 ? (number[1].Length>4? number[1].Substring(0,4):number[1]): "0000"));
        //Output: 50234.9489

        Console.ReadKey();
    }
}

答案 3 :(得分:0)

这里有很多答案可以解决问题中给出的输入,但是在使用一系列值测试它们时,它们都有局限性(参见注释)。

我可以通过任何十进制输入看到实现此目的的唯一方法如下。它可能不是一个班轮,但对我来说似乎很健壮。

private static string TrimDecimalPlaces(double value, int numberOfDecimalPlaces)
{
    string valueString = value.ToString();

    if (!valueString.Contains(".")) return valueString;

    int indexOfDot = valueString.IndexOf(".");

    if ((indexOfDot + numberOfDecimalPlaces + 1) < valueString.Length)
    {
        return valueString.Remove(indexOfDot + numberOfDecimalPlaces + 1);
    }
    return valueString;
}

我用以下测试数据对此进行了测试,结果与预期一致:

  • 1
  • 1.1
  • 1.11
  • 1.111
  • 1.1111
  • 1.11111
  • 1.111111
  • -1
  • -1.1
  • -1.11
  • -1.111
  • -1.1111
  • -1.11111
  • -1.111111
相关问题