2016-09-25 62 views
0

我需要一个函数来检索价格很好格式化插入到数据库。数据库只接受点作为小数点分隔符,不能有千位分隔符。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)); 
} 

问题和疑问我现在面临:

  1. 有什么办法(Linq中或东西) - 除环 - 要添加的剩余#?
  2. MoneyToDatabase("15,00", 2)回报1500,应该回到15.00
  3. MoneyToDatabase("15,00", 5)回报1500,应该返回15.00000
  4. 我不知道什么'0:'意味着
+0

你有没有尝试过使用Double.TryParse? – Steve

+0

我刚刚给了一个尝试,并在调试时看到转换时(使用'Double.TryParse'或'Convert.ToDouble')它会自动将'15.00'设置为'1500.0' – Linesofcode

回答

0

解决

实际的问题是CultureInfo,我发现我可以使用“F2”,“F3”,并将检索小数位,因为我想要的。

public static string MoneyToDatabase(string value, int decimal_places) 
{ 
    if(string.IsNullOrEmpty(value) == true) 
     return "0.00"; 

    value = value.Replace(",", "."); 

    string format = "F" + decimal_places; 

    double valueAsDouble; 
    double.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out valueAsDouble); 

    // It sets again a comma in the string and must be replaced 
    return valueAsDouble.ToString(format).Replace(",", "."); 
} 
0

您可以使用转换象下面这样:

float.Parse("1,000.25", NumberStyles.AllowThousands); 
float.Parse("1000.25", NumberStyles.AllowThousands); 
1000,25 you can replace it ;). 

请注意,如果你使用不同的文化,那么文化不变。

+0

这不起作用,因为:1。 'float v = float.Parse(value,NumberStyles.AllowThousands);''返回'1500.0'和2.如何设置5位小数位? – Linesofcode