user4227915
user4227915

Reputation:

Double to String with less decimals as possible and at least four

I have a function that returns a double value.

How to take its integer part plus decimal part but removing right zeroes and another digit if it is after fourth decimal place?

21.879653    // 21.8796
21.000000    // 21
21.020000    // 21.02

I tried using regex:

Regex.Replace(
    Regex.Match(result.ToString(), @"^\d+(?:\.\d{4})?").Value,
    @"0*$", "");

But I haven't had any luck... and I'm sure this is not a task for regex.

Other ideas?

Upvotes: 0

Views: 163

Answers (3)

Chris S.
Chris S.

Reputation: 161

Try this. It writes nothing for zero.

internal class Program
{
    static void Main()
    {
        double d = 21.8786;
        double d1 = 21.000;
        double d2 = 21.02000;
        double d3 = 0;

        WriteNameAndValue(nameof(d), d.FormatDoubleToFourPlaces());
        WriteNameAndValue(nameof(d1), d1.FormatDoubleToFourPlaces());
        WriteNameAndValue(nameof(d2), d2.FormatDoubleToFourPlaces());
        WriteNameAndValue(nameof(d3), d3.FormatDoubleToFourPlaces());

    }

    static void WriteNameAndValue(string name, string value)
    {
        Console.WriteLine($"Name:  {name}\tValue: {value}");
    }


}

 static class DoubleHelper
{
    public static string FormatDoubleToFourPlaces(this double d, CultureInfo ci = null)
    {
        const int decimalPlaces = 4;


        if (double.IsInfinity(d) || double.IsNaN(d))
        {
            var ex = new ArgumentOutOfRangeException(nameof(d), d, "Must not be NaN or infinity");
            throw ex;
        }
        decimal decimalVersion = Convert.ToDecimal(d);
        if (decimalVersion == 0)
        {
            return string.Empty;
        }

        int integerVersion = Convert.ToInt32(Math.Truncate(decimalVersion));
        if (integerVersion == decimalVersion)
        {
            return integerVersion.ToString();
        }
        decimal scaleFactor = Convert.ToDecimal(Math.Pow(10.0, decimalPlaces));

        decimal scaledUp = decimalVersion*scaleFactor;
        decimal truncatedScaledUp = Math.Truncate(scaledUp);

        decimal resultingVersion = truncatedScaledUp/scaleFactor;

        return resultingVersion.ToString(ci ?? CultureInfo.InvariantCulture);

    }
}

Upvotes: 0

Dirk Trilsbeek
Dirk Trilsbeek

Reputation: 6023

you can use Math.Truncate to remove the unwanted digits. If you only want 4 digits:

double d = 21.879653;
double d2 = Math.Truncate(d * 10000) / 10000;

Console.WriteLine(d2.ToString("#.####"));

Upvotes: 0

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

Instead of icky string manipulations, you can just use the standard .NET Numeric Format Strings:

"#"
Digit placeholder
Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string.

    double a = 21.879653;  
    double b = 21.000000;   
    double c = 21.020000;   

    Console.WriteLine(a.ToString("#0.####"));
    Console.WriteLine(b.ToString("#0.####"));
    Console.WriteLine(c.ToString("#0.####"));

https://dotnetfiddle.net/n9xrfU

The format specifier before the decimal point is #0, meaning at least one digit will be displayed.

Upvotes: 4

Related Questions