如何将字符串转换为十进制 [英] How to convert string to decimal

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

问题描述

我想将字符串转换为十进制我尝试这么多组合不能得到正确的数字。

字符串a =14,8;

字符串b =10 ,36;



我尝试过:



I want to convert string to decimal i try so many combination cant get right number.
string a = "14,8";
string b = "10,36";

What I have tried:

string a = "14,8";
string b = "10,36";



decima c = MyClass.CustomDecimalParse(string value); //我得到148和1036 WHYYYY !! ??


decima c = MyClass.CustomDecimalParse(string value); //i got 148 and 1036 WHYYYY!!??

public static decimal CustomDecimalParse(string value)
        {
            decimal number = 0;
            return Decimal.TryParse(value, out number) ? number : 0;
        }

推荐答案

您需要使用文化样式和格式化程序,因为您的数字格式不是默认格式。请参阅 Decimal.TryParse Method(System)| Microsoft Docs [ ^ ]。
You need to use a culture style and formatter, as your number formats are not the default. See Decimal.TryParse Method (System) | Microsoft Docs[^].


这是全球化的事情。在一种文化中,1,234是1234,而在另一种文化中,它是1.234。计算机正在使用它当前的文化,以便可能在某些地方,操作系统等设置中。如果您想使用特定的文化,那么在您的TryParse方法中提供它。例如,如果您使用德语(de)将14,8识别为14.8。因此,请使用您的预期文化或更改代码运行的上下文的一般文化。



This is a globalisation thing. In one culture "1,234" is 1234 and in another it is 1.234. The computer is using whatever its current culture is so that might be in the settings somewhere, in the OS etc. If you want to use a specific culture then supply it in your TryParse method. For example if you use German (de) that recognises "14,8" as "14.8". So use your intended culture or change the general culture of the context your code runs in.

public static decimal CustomDecimalParse(string value)
{
    decimal number = 0;
    return Decimal.TryParse(value, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.GetCultureInfo("de-DE"), out number) ? number : 0;
}


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

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