字符串转换为十进制,保持分数 [英] Convert string to decimal, keeping fractions

查看:116
本文介绍了字符串转换为十进制,保持分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换 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));
    }
}

这篇关于字符串转换为十进制,保持分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆