用字符串中的美分获得美元价值的最佳方法是什么?

时间:2016-11-11 23:24:51

标签: c# asp.net .net vb.net

我希望获得最优雅的解决方案(最少量的类型代码),以便将一分钱字符串转换为美元分值。它必须代表美分(.00),因此除以100并不是直截了当的。例如,“00000600000”必须表示为“6000.00”。我已经制作了以下方法:

value = Math.Abs(Int(Mid(Mid(line, 188, 11), 1, Len(Mid(line, 188, 11)) - 2))) & "." & Mid(Mid(line, 188, 11), Len(Mid(line, 188, 11)) - 1, 2) 

value = (Math.Abs(Int(Mid(line, 188, 11))).ToString).Insert(Math.Abs(Int(Mid(line, 188, 11))).ToString.Length - 2, ".")

value = Math.Abs(Int(Mid(line, 188, 11))) : value = value.Insert(value.Length - 2, ".") 

2 个答案:

答案 0 :(得分:3)

int cents = int.Parse(line);
decimal dollars = cents / 100m;
string value = dollars.ToString("$#.00");

或者,如果您对优雅的定义意味着“更少的行”:

value = (int.Parse(line) / 100m).ToString("$#.00");

答案 1 :(得分:0)

尝试以下

Dim str as string = "0006500000"
Dim d as decimal = cdec(str) / 100
Msgbox(d.tostring("#.##"))