[英]Parse string to decimal, commas and periods
How to parse string to decimal so it would work for both formats - w/ commas and periods?如何将字符串解析为十进制,以便它适用于两种格式 - 带逗号和句点?
[Fact]
public void foo(){
var a="1,1";
var b="1.1";
Assert.Equal(Parse(a),Parse(b));
}
private decimal Parse(string s){
return decimal.Parse(s,NumberStyles.Any,
CultureInfo.InvariantCulture);
}
output: output:
Test 'Unit.Sandbox.foo' failed: Assert.Equal() Failure
Expected: 11
Actual: 1,1
You could try that:你可以试试:
private decimal Parse(string s){
s = s.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
return decimal.Parse(s,NumberStyles.Any,
CultureInfo.InvariantCulture);
}
How about this?这个怎么样?
private static decimal Parse(string s)
{
s = s.Replace(",", ".");
return decimal.Parse(s);
}
You should get the desired result by modifying the Currency decimal separator to a comma before a parse on a comma decimal string.您应该通过在解析逗号十进制字符串之前将货币小数分隔符修改为逗号来获得所需的结果。 There are some food resources here:这里有一些食物资源:
http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencydecimalseparator.aspx#Y888 http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencydecimalseparator.aspx#Y888
You could alternatively implement your own Iformatprovider as discussed here:您也可以按照此处讨论的方式实现自己的 Iformatprovider:
http://msdn.microsoft.com/en-us/library/t7xswkc6.aspx http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx http://msdn.microsoft.com/en-us/library/t7xswkc6.aspx http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx
Oh, or you could do a dirty hack and simply run a string replace on "," with ".";)哦,或者你可以做一个肮脏的黑客,简单地在“,”上用“。”运行字符串替换;)
If you have an English-language operating system, this method converts a decimal number with a comma to a dot.如果您有英语操作系统,此方法会将带逗号的十进制数转换为点。 If you have Russian, the method converts a decimal number with a dot to a comma.如果您有俄语,该方法会将带点的十进制数转换为逗号。
Console.Write("Input number: ");
string? input = Console.ReadLine();
decimal number = ConvertNumberToCurrentLocale(input);
Console.WriteLine("Result: " + number);
decimal ConvertNumberToCurrentLocale(string? input)
{
string separator = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
switch (separator)
{
case ".":
input = input?.Replace(",", ".");
break;
case ",":
input = input?.Replace(".", ",");
break;
}
decimal.TryParse(input, out var number);
return number;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.