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

问题描述

我需要一个字符串转换为C#小数,但这个字符串有不同的格式

I need convert a String to a decimal in C#, but this string have different formats.

例如:

50085

500,85

500.85

这应该是十进制转换为500,85。有一个简单的形式使用的格式要做到这一点皈依?

This should be convert for 500,85 in decimal. Is there is a simplified form to do this convertion using format?

推荐答案

虽然decimal.Parse()是你正在寻找方法对,你将不得不提供更多的信息给它。它不会自动在3格式你给挑之间,你必须告诉它的格式你期待(在的IFormatProvider的形式)。请注意,即使使用的IFormatProvider,我不认为50085将在适当拉。

While decimal.Parse() is the method you are looking for, you will have to provide a bit more information to it. It will not automatically pick between the 3 formats you give, you will have to tell it which format you are expecting (in the form of an IFormatProvider). Note that even with an IFormatProvider, I don't think "50085" will be properly pulled in.

我看到的唯一一致的是,它从你的例子看来,你总是期望的精度小数点后两位。如果是这样的话,你可以去掉所有的句号和逗号,然后除以100

The only consistent thing I see is that it appears from your examples that you always expect two decimal places of precision. If that is the case, you could strip out all periods and commas and then divide by 100.

也许是这样的:

public decimal? CustomParse(string incomingValue)
{
    decimal val;
    if (!decimal.TryParse(incomingValue.Replace(",", "").Replace(".", ""), NumberStyles.Number, CultureInfo.InvariantCulture, out val))
        return null;
    return val / 100;
}

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

08-24 10:46