简体   繁体   English

c#将字符串值转换为十进制的正确方法

[英]c# Correct way to convert string value to decimal

I need convert the any value in format "101.46" to decimal . 我需要将格式为“ 101.46”的任何值转换为小数

string s = "101.46";
decimal value = Convert.ToDecimal(s);

But the decimal final value is always 10146 . 但是十进制最终值始终是10146 I need the format of the output value to be 101.46 as decimal 我需要将输出值的格式设置为十进制101.46

Convert.ToDecimal will use the currently executing thread's culture - and my guess is that in your case, that's a culture that uses , as the decimal separator rather than . Convert.ToDecimal将使用当前线程的文化-我的猜测是,在你的情况,这是使用一种文化,作为小数点分隔符,而不是. . You just need to specify the right culture - which is often the invariant culture - that's almost always the right culture to use for any strings that are intended to be machine-readable. 您只需要指定正确的区域性-通常是不变区域性 -几乎总是适合打算用于机器可读字符串的正确区域性。 (You should use the invariant culture for creating such strings too.) (您也应该使用不变的文化来创建这样的字符串。)

I'd generally recommend using the static Parse methods over Convert.ToXyz (as they're often more capable, and have TryParse options too), so while you could pass the invariant culture to Convert.ToDecimal , I'd use: 我通常建议在Convert.ToXyz使用静态Parse方法(因为它们通常更强大,并且也具有TryParse选项),因此尽管可以将不变的区域性传递给Convert.ToDecimal ,但我会使用:

decimal value = decimal.Parse(text, CultureInfo.InvariantCulture);

您当前的区域性似乎使用,作为小数点分隔符,那么您可以使用:

decimal value = decimal.Parse(s, CultureInfo.InvariantCulture);
public static boolean isNumeric(String str)  
{  
  try  
  {  
    decimal d = decimal.parseDouble(str);  
  }  
  catch(NumberFormatException nfe)  
  {  
    return false;  
  }  
  return true;  
}

If you want to use regular expression you can use as below, 如果您想使用正则表达式,可以按以下方式使用,

public static boolean isNumeric(String str)
{
  return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
}

If function returns true then 如果函数返回true,则

if(isNumeric(Yourvalue)){
  decimal value = decimal.Parse(s, CultureInfo.InvariantCulture);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM