将字符串转换为十进制,保留分数


71

我正在尝试转换1200.00decimal,但Decimal.Parse()将其删除.00。我尝试了一些不同的方法,但是它总是删除.00,除非我提供的分数不为0。

string value = "1200.00";

方法1

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

方法2

 var convertDecimal = Convert.ToDecimal(value);

方法3

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

如何将string包含转换1200.00decimal包含1200.00


我认为零是隐式的。即使没有看到,“。00”部分也以小数存在。出于格式化目的,您应该显示它们,而不必担心。
尼尔森·米兰达

6
@nmiranda:不,decimal保持适当的规模。decimal.Parse("1200.000")并且decimal.Parse("1200.00")将返回不同的值,保留尾随0的数量。
乔恩·斯基特

1
我同意@NelsonMiranda。事实上decimal.Parse(“1200.000”)等于(decimal.Parse(“1200.00”))返回true,所以我没有看到这个问题的地步....
三月酒吧

1
我可以确认这是非美国本地化的问题。我的电脑设置了意大利语语言环境和decimal.Parse(“ 1200.00”)返回120000,而decimal.Parse(“ 1200,00”)返回1200.00
lebenf

Answers:


92

嗯...我无法重现此内容:

using System;

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

您确定不是代码的其他部分稍后将十进制值标准化吗?

以防万一是文化方面的问题,请尝试完全不依赖您的语言环境的此版本:

using System;
using System.Globalization;

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

1
是的::十进制d =十进制.Parse(“ 1200.000”); Console.WriteLine(d); //打印1200.000,因此这不是文化性的事情。
basarat

投下

4
尝试更改“。” 小数点分隔符为','。如果结果不同,那是文化上的事情。
Coyolero 2014年

12

我认为您的问题是显示小数而不是内容时。

如果你试试

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

s 将包含字符串 "1200"

但是,如果您将代码更改为此

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

s 将包含字符串 "1200.00"您想要。

编辑

看来我今天一大早就要死了。我添加了Parse现在语句。但是,即使我的第一个代码也会输出“ 1200.00”,即使我希望它输出“ 1200”也是如此。似乎我每天都在学习一些东西,在这种情况下,显然这是非常基础的。

因此,请忽略此正确答案。在这种情况下,我们可能需要更多代码来识别您的问题。


2
@Øyvind-decimal内部表示形式存储小数点后的零,即使在数学上它们不相关。因此,尽管decimal.Parse("1200.00") == decimal.Parse("1200").ToString()值分别为“1200.00”和“1200”。OP不需要在.ToString()方法中指定小数位。

@Enigmativity-感谢您的解释:)感觉就像我早就应该知道的东西
–ØyvindBråthen10年

12

您好,我遇到了同样的问题,但是很简单,只需执行以下操作:

string cadena="96.23";

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

我认为这是因为在十进制数字上接受C#的符号带有“,”


你确定吗?它似乎取决于机器设置。
vCillusion

5

下面的代码将值打印为1200.00。

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

不确定您期望什么?


5

使用CultureInfo类对我有用,希望对您有所帮助。

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

2

使用这个例子

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

2

这是我为自己想出的解决方案。这已准备好作为命令提示符项目运行。如果没有,您需要清洁一些东西。希望这可以帮助。它接受几种输入格式,例如:1.234.567,89 1,234,567.89等

    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

即使打印的表示形式不是您期望的值,该值也相同:

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

0

您可以尝试在程序中调用此方法:

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
    }

例:

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

0

十进制d = 3.00仍为3。我想您要在屏幕上的某些位置显示它或将其作为3.00打印在日志文件上。您可以执行以下操作

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

或者,如果您使用数据库存储小数,则可以在数据库中设置精度值。


-4

这就是你要做的。

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

// value = "1200.00" 

这对我有用。谢谢。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.