[c#] Convert string to decimal, keeping fractions

I am trying to convert 1200.00 to decimal, but Decimal.Parse() removes .00. I've tried some different methods, but it always removes .00, except when I supply a fraction different than 0.

string value = "1200.00";

Method 1

 var convertDecimal = Decimal.Parse(value ,  NumberStyles.AllowThousands
       | NumberStyles.AllowDecimalPoint | NumberStyles.AllowCurrencySymbol);

Method 2

 var convertDecimal = Convert.ToDecimal(value);

Method 3

var convertDecimal = Decimal.Parse(value,
       NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture);

How can I convert a string containing 1200.00 to a decimal containing 1200.00?

This question is related to c# string decimal

The answer is


Hello i was have the same issue, but it is easly, just do this:

string cadena="96.23";

decimal NoDecimal=decimal.parse(cadena.replace(".",","))

I think this is beacuse the notation that accept C# on decimal numbers are with a ","


Use this example

System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("en-GB",true);

decimal currency_usd = decimal.Parse(GetRateFromCbrf("usd"),culInfo);
decimal currency_eur = decimal.Parse(GetRateFromCbrf("eur"), culInfo);

this is what you have to do.

decimal d = 1200.00;    
string value = d.ToString(CultureInfo.InvariantCulture);

// value = "1200.00" 

This worked for me. Thanks.


decimal d = 3.00 is still 3. I guess you want to show it some where on screen or print it on log file as 3.00. You can do following

string str = d.ToString("F2");

or if you are using database to store the decimal then you can set pricision value in database.


The use of CultureInfo class worked for me, I hope help you.

    string value = "1200.00";
    CultureInfo culture = new CultureInfo("en-US");
    decimal result = Convert.ToDecimal(value, culture);

I think your problem is when displaying the decimal, not the contents of it.

If you try

string value = "1200.00";
decimal d = decimal.Parse(s);
string s = d.ToString();

s will contain the string "1200".

However if you change your code to this

string value = "1200.00";
decimal d = decimal.Parse(s);
string s = d.ToString("0.00");

s will contain the string "1200.00" as you want it to do.

EDIT

Seems I'm braindead early in the morning today. I added the Parse statements now. However even my first code will output "1200.00", even if I expected it to output "1200". Seems like I'm learning something each day, and in this case obviously something that is quite basic.

So disregard this a an proper answer. We will probably need more code to identify your problem in this case.


Hmm... I can't reproduce this:

using System;

class Test
{
    static void Main()        
    {
        decimal d = decimal.Parse("1200.00");
        Console.WriteLine(d); // Prints 1200.00
    }
}

Are you sure it's not some other part of your code normalizing the decimal value later?

Just in case it's cultural issues, try this version which shouldn't depend on your locale at all:

using System;
using System.Globalization;

class Test
{
    static void Main()        
    {
        decimal d = decimal.Parse("1200.00", CultureInfo.InvariantCulture);
        Console.WriteLine(d.ToString(CultureInfo.InvariantCulture));
    }
}

Here is a solution I came up with for myself. This is ready to run as a command prompt project. You need to clean some stuff if not. Hope this helps. It accepts several input formats like: 1.234.567,89 1,234,567.89 etc

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Globalization;
    using System.Linq;

    namespace ConvertStringDecimal
    {
        class Program
        {
            static void Main(string[] args)
            {
                while(true)
                {
                    // reads input number from keyboard
                    string input = Console.ReadLine();
                    double result = 0;
                    // remove empty spaces
                    input = input.Replace(" ", "");
                    // checks if the string is empty
                    if (string.IsNullOrEmpty(input) == false)
                    {
                        // check if input has , and . for thousands separator and decimal place
                        if (input.Contains(",") && input.Contains("."))
                        {
                            // find the decimal separator, might be , or .
                            int decimalpos = input.LastIndexOf(',') > input.LastIndexOf('.') ? input.LastIndexOf(',') : input.LastIndexOf('.');
                            // uses | as a temporary decimal separator
                            input = input.Substring(0, decimalpos) + "|" + input.Substring(decimalpos + 1);
                            // formats the output removing the , and . and replacing the temporary | with .
                            input = input.Replace(".", "").Replace(",", "").Replace("|", ".");
                        }
                        // replaces , with .
                        if (input.Contains(","))
                        {
                            input = input.Replace(',', '.');
                        }
                        // checks if the input number has thousands separator and no decimal places
                        if(input.Count(item => item == '.') > 1)
                        {
                            input = input.Replace(".", "");
                        }
                        // tries to convert input to double
                        if (double.TryParse(input, out result) == true)
                        {
                            result = Double.Parse(input, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, CultureInfo.InvariantCulture);
                        }
                    }
                    // outputs the result
                    Console.WriteLine(result.ToString());
                    Console.WriteLine("----------------");
                }
            }
        }
    }

The value is the same even though the printed representation is not what you expect:

decimal d = (decimal )1200.00;
Console.WriteLine(Decimal.Parse("1200") == d); //True

You can try calling this method in you program:

static double string_double(string s)
    {
        double temp = 0;
        double dtemp = 0;
        int b = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] == '.')
            {
                i++;
                while (i < s.Length)
                {
                    dtemp = (dtemp * 10) + (int)char.GetNumericValue(s[i]);
                    i++;
                    b++;
                }
                temp = temp + (dtemp * Math.Pow(10, -b));
                return temp;
            }
            else
            {
                temp = (temp * 10) + (int)char.GetNumericValue(s[i]);
            }
        }
        return -1; //if somehow failed
    }

Example:

string s = "12.3";
double d = string_double (s);        //d = 12.3 

The below code prints the value as 1200.00.

var convertDecimal = Convert.ToDecimal("1200.00");
Console.WriteLine(convertDecimal);

Not sure what you are expecting?