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

83

我试图将 1200.00 转换为 decimal,但是 Decimal.Parse() 方法会将 .00 去掉。我尝试了一些不同的方法,但总是会去掉 .00,除非我提供一个非零小数。

string value = "1200.00";

方法一

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

方法二

 var convertDecimal = Convert.ToDecimal(value);

方法三

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

如何将包含 1200.00string 转换为包含 1200.00decimal 呢?


我认为零是隐含的。即使您看不到它们,".00"部分也存在于小数中。为了格式化目的,您应该显示它们,但是您不必担心。 - Nelson Miranda
6
不,decimal会保持适当的精度。decimal.Parse("1200.000")decimal.Parse("1200.00")将返回不同的值,保留末尾0的数量。 - Jon Skeet
1
我同意@NelsonMiranda的观点。事实上,decimal.Parse("1200.000").Equals(decimal.Parse("1200.00"))返回true,所以我不明白这个问题的意义... - Mar Bar
1
我可以确认这是非美国化本地化的一个问题。如果我的电脑设置为意大利语环境,decimal.Parse("1200.00")返回120000,而decimal.Parse("1200,00")则返回1200.00。 - lebenf
12个回答

104

嗯...我无法重现这个问题:

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
是的,而且: decimal d = decimal.Parse("1200.000"); Console.WriteLine(d); // 输出 1200.000 所以这不是一个文化问题。 - basarat
点赞,有疑问请在下方评论区说明 - Theofanis Pantelides
5
尝试将小数点 '.' 替换为 ','。如果结果不同,那就是一种文化差异。 - Coyolero

15

你好,我曾经遇到过同样的问题,但它很容易解决,只需执行以下操作:

string cadena="96.23";

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

我认为这是因为C#在十进制数上接受的符号是“,”而不是“。”


你确定吗?似乎取决于机器设置。 - vCillusion
我知道这非常古老,但使用逗号而不是句点很可能是本地化。一些国家使用句点,而另一些国家则使用逗号作为“小数点”。 - TSmith

13
我认为你的问题出在显示小数时,而不是其内容上。
如果你尝试使用以下代码:
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"。看来我每天都在学习一些东西,而在这种情况下显然是一些相当基础的东西。

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


3
“decimal” 内部表示法会存储小数点后的零位,尽管在数学上它们是无关紧要的。因此,虽然 decimal.Parse("1200.00") == decimal.Parse("1200"),但它们的 .ToString() 值分别为 "1200.00" 和 "1200"。原帖作者不需要在 .ToString() 方法中指定小数位数。 - Enigmativity
1
@Enigmativity - 谢谢您的解释 :) 这感觉像是我很久以前就应该知道的事情... - Øyvind Bråthen

10

CultureInfo类的使用对我很有帮助,希望能为您提供帮助。

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

5
下面的代码将输出值为1200.00。
var convertDecimal = Convert.ToDecimal("1200.00");
Console.WriteLine(convertDecimal);

Not sure what you are expecting?


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

1

以下代码移除空格/字母并检查文化。无论小数分隔符是.还是,,都会转换为十进制并返回值。

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

0

尽管打印出来的表示不是您所期望的,但值仍然相同:

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

0

decimal d = 3.00仍然是3。 我猜你想在屏幕上显示它或将其作为3.00打印在日志文件中。 你可以这样做:

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接