How to parse a numerical string to decimal and convert it back to the string without any loss?

Viewed 131

How to parse a numerical string input to decimal number and convert it back to the string without any loss?

using System;
using System.Globalization;


class Program
{
    static void Main(string[] args)
    {
        string input = "-1.234.567.890,123456789012345678901234567890";
        var ci = new CultureInfo("id-ID");

        decimal number = decimal.Parse(input, NumberStyles.Number, ci);
        string output = number.ToString("N", ci);

        Console.WriteLine(output == input);// produces False

    }
}

Here I am learning how to parse and convert with the simplest way.

2 Answers

Created a class of MyType to hold your number and split the input into the two different sections.

You might have trouble if you plan on using these numbers for arithmetic. You probably have to overload the arithmetic operations and implement your own.

public static void Main()
{
    // Mine
    string input = "-1.234.567.890,123456789012345678901234567890";
    string left = input.Split(',')[0].Replace(".", string.Empty);
    string right = input.Split(',')[1];

    MyType myInput = new MyType(
        int.Parse(left, System.Globalization.NumberStyles.AllowLeadingSign), 
        BigInteger.Parse(right, System.Globalization.NumberStyles.AllowLeadingSign));

    Console.WriteLine(input);
    Console.WriteLine(myInput);

    Console.WriteLine(input == myInput.ToString());

    // Yours
    string input2 = "-1.234.567.890,123456789012345678901234567890";
    var ci = new CultureInfo("id-ID");

    decimal number = decimal.Parse(input2, NumberStyles.Number, ci);
    string output = number.ToString("N", ci);

    Console.WriteLine(input2);
    Console.WriteLine(output);
    Console.WriteLine(output == input2);// produces False
}

public class MyType
{
    public int whole;
    public BigInteger deci;

    public MyType(int whole, BigInteger deci)
    {
        this.whole = whole;
        this.deci = deci;
    }

    public override string ToString()
    {
        return string.Format("{0},{1}", string.Format("{0:#,####}", whole)
                     .Replace(',' ,'.'), deci);
    }
}

// Mine
-1.234.567.890,123456789012345678901234567890
-1.234.567.890,123456789012345678901234567890
True
// Yours
-1.234.567.890,123456789012345678901234567890
-1.234.567.890,12
False
Related