我需要一个函数来检索价格很好格式化插入到数据库。数据库只接受点作为小数点分隔符,不能有千位分隔符。c#格式价格数据库与变型小数位
1,000.25 -> is not valid
1000.25 -> is valid
1000,25 -> is valid (but will be converted ',' to '.')
然而,并非所有列都有2位小数,有些列可以有5位小数。
public static double MoneyToDatabase(string value, int decimal_places)
{
if(string.IsNullOrEmpty(value) == true)
return 0.00;
value = value.Replace(",", "."); // converts the comma into dot
string cardinal = "##";
if(decimal_places > 2)
for(int i = 3; i <= decimal_places; i++)
cardinal += "#";
return Convert.ToDouble(string.Format("{0:0." + cardinal + "}", value));
}
问题和疑问我现在面临:
- 有什么办法(Linq中或东西) - 除环 - 要添加的剩余#?
MoneyToDatabase("15,00", 2)
回报1500,应该回到15.00MoneyToDatabase("15,00", 5)
回报1500,应该返回15.00000- 我不知道什么
'0:'
意味着
你有没有尝试过使用Double.TryParse? – Steve
我刚刚给了一个尝试,并在调试时看到转换时(使用'Double.TryParse'或'Convert.ToDouble')它会自动将'15.00'设置为'1500.0' – Linesofcode