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

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

问题描述:

我想转换 1200.00 小数,但 Decimal.Parse() .00 。我已经尝试了一些不同的方法,但它始终删除 .00 ,除非我提供比0不同的一小部分。

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



方法1



Method 1

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



方法2



Method 2

 var convertDecimal = Convert.ToDecimal(value);



方法3



Method 3

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



我怎么能转换字符串包含 1200.00 到小数含> 1200.00

嗯......我不能重现此:

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