Convert string to decimal, keeping fractions

后端 未结 11 1257
走了就别回头了
走了就别回头了 2020-11-28 13:31

I am trying to convert 1200.00 to decimal, but Decimal.Parse() removes .00. I\'ve tried some different methods, but it al

相关标签:
11条回答
  • 2020-11-28 13:36

    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.

    0 讨论(0)
  • 2020-11-28 13:38

    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.

    0 讨论(0)
  • 2020-11-28 13:41

    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
    
    0 讨论(0)
  • 2020-11-28 13:43

    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));
        }
    }
    
    0 讨论(0)
  • 2020-11-28 13:46

    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("----------------");
                    }
                }
            }
        }
    
    0 讨论(0)
  • 2020-11-28 13:47

    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 
    
    0 讨论(0)
提交回复
热议问题