简体   繁体   English

十进制解析各种字符串

[英]Decimal.Parse various strings

Hello I might have strings for example "1,1" or "1.1" or "1" or "" and from each of them I need to get results in same format so it can be saved in SQL Db as numeric (8,2) 您好,我可能有一些字符串,例如"1,1""1.1""1""" ,我需要从每个字符串中获取相同格式的结果,以便可以将其保存为SQL Db中的数字(8,2 )

var ci = CultureInfo.InvariantCulture.Clone() as CultureInfo;
            prikaz.Parameters.AddWithValue("@p_ub_c", Decimal.Parse(p_ub_c.Text.Replace(',', '.') == string.Empty ? "0.00" : p_ub_c.Text, ci));

Passed string is: "2500,00" but can be also "" or "2500.00" 传递的字符串是: "2500,00"但也可以是"""2500.00"

Those values needs to be saved in sql numeric(8,2) And when the textbox p_ub_cis empty then string is 0 and I got this: System.FormatException input string was not in correct format. 这些值需要保存在sql numeric(8,2)中,当文本框p_ub_cis空时,字符串为0,我得到了以下信息:System.FormatException输入的字符串格式不正确。

May someone help me solve this out? 有人可以帮我解决这个问题吗?

Thank you for your time 感谢您的时间

Your problem lies with the follow code fragment: 您的问题在于以下代码片段:

p_ub_c.Text.Replace(',', '.') == string.Empty ? "0.00" : p_ub_c.Text

This says 'take my Text and replace "," with ".", then if the result is an empty string, use "0.00", otherwise use Text'. 这说“取我的文字,然后用“。”替换“,”,然后如果结果为空字符串,请使用“ 0.00”,否则请使用“文字”。 In other words, you lose the result of the Replace. 换句话说,您将丢失替换的结果。

If you change it to store the results of the Replace and parse that, it should fix the problem. 如果更改它以存储“替换”的结果并对其进行解析,则应该可以解决此问题。 Beware of someone entering eg "1,000.1" though as you'll end up with "1.000.1", which is still an invalid number. 提防有人输入例如“ 1,000.1”,因为您最终会得到“ 1.000.1”,这仍然是无效数字。

您永远不会使用Replace返回的内容,应按以下方式使用它:

string.IsNullOrEmpty(p_ub_c.Text) ? "0.00" : p_ub_c.Text.Replace(',', '.');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM