Convert string to decimal, keeping fractions

C#StringDecimal

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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));
    }
}

Solution 2 - C#

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 ","

Solution 3 - C#

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.

Solution 4 - C#

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

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

Solution 5 - C#

The below code prints the value as 1200.00.

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

Not sure what you are expecting?

Solution 6 - C#

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);

Solution 7 - C#

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("----------------");
                }
            }
        }
    }

Solution 8 - C#

Below code remove spaces/letters and checks culture. No matter decimal separator . or , converts to decimal and returns value.

public decimal convertToDecimal(String str)
{
    // Decimal separator is ",".
    CultureInfo culture = new CultureInfo("tr-TR");
    // Decimal sepereator is ".".
    CultureInfo culture1 = new CultureInfo("en-US");
    // You can remove letters here by adding regex expression.
    str = Regex.Replace(str, @"\s+|[a-z|A-Z]", "");
    decimal result = 0;
    var success = decimal.TryParse(str, NumberStyles.AllowThousands |
        NumberStyles.AllowDecimalPoint, culture, out result);
    // No need NumberStyles.AllowThousands or
    // NumberStyles.AllowDecimalPoint but I used:
    decimal result1 = 0;
    var success1 = decimal.TryParse(str, NumberStyles.AllowThousands |
        NumberStyles.AllowDecimalPoint, culture1, out result1);
    if (success && success1)
    {
        if (result > result1)
            return result1;
        else
            return result;
    }
    if (success && !success1)
        return result;
    if (!success && success1)
        return result1;
    return 0;
}
USAGE var decimal = convertToDecimal(string);

Solution 9 - C#

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

Solution 10 - C#

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 

Solution 11 - C#

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.

Solution 12 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNETQuestionView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#Adan NetDevView Answer on Stackoverflow
Solution 3 - C#Øyvind BråthenView Answer on Stackoverflow
Solution 4 - C#Juan CarlosView Answer on Stackoverflow
Solution 5 - C#RameshView Answer on Stackoverflow
Solution 6 - C#Aleksey RadzhabovView Answer on Stackoverflow
Solution 7 - C#Paulo VerissimoView Answer on Stackoverflow
Solution 8 - C#user16926734View Answer on Stackoverflow
Solution 9 - C#KingCodeView Answer on Stackoverflow
Solution 10 - C#user7507137View Answer on Stackoverflow
Solution 11 - C#A.LearnView Answer on Stackoverflow
Solution 12 - C#Dimuthu RanmalView Answer on Stackoverflow