将字符串解析为小数、逗号和句点
如何将字符串解析为十进制,以便它适用于两种格式 - 带逗号和句点?
[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);
}
输出:
Test 'Unit.Sandbox.foo' failed: Assert.Equal() Failure
Expected: 11
Actual: 1,1
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:
Test 'Unit.Sandbox.foo' failed: Assert.Equal() Failure
Expected: 11
Actual: 1,1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以尝试这样做:
You could try that:
这个怎么样?
How about this?
您应该通过在解析逗号小数字符串之前将货币小数分隔符修改为逗号来获得所需的结果。这里有一些食物资源:
http:// msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencydecimalseparator.aspx#Y888
您也可以实现自己的 Iformatprovider,如下所述:
http://msdn.microsoft.com/en-us/library/t7xswkc6.aspx
http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx
哦,或者你可以做一个肮脏的黑客,只需在“,”上运行一个字符串替换为“。” ;)
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
You could alternatively implement your own Iformatprovider as discussed here:
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.