我想从两个字符串中获取小数值,例如500.45
。如何实现这个操作?
decimal value; //like 500.45
string txt1, txt2;
txt1 = "500";
txt2 = "45";
value = Convert.ToDecimal(txt1) + Convert.ToDecimal(txt2); //500.45
答案 0 :(得分:0)
string txt1, txt2;
txt1 = "500";
txt2 = "45";
decimal value = Convert.ToDecimal(string.Format("{0}.{1}", txt1, txt2));
答案 1 :(得分:0)
试试这个:
decimal val;
string txt1 = "500";
string txt2 = "45";
string textValue = txt1 + "." + txt2;
decimal.TryParse(textValue,
NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture,
out val);
答案 2 :(得分:0)
value = Convert.ToDecimal(txt1 + "." + txt2);
答案 3 :(得分:0)
显然,每个人都能想到的唯一答案就是琐碎的答案(在两者之间连接并解析它)。但是,做得对,拜托! (我提供了足够的提示!)例如,在我的系统上,小数点分隔符是逗号,因此所有代码都不起作用。你必须在中性文化中做到这一点,例如:
string integerPart = "500";
string fractionalPart = "45";
decimal result = Decimal.Parse(
// Combine the strings to a new string "500.45"
String.Format("{0}.{1}", integerPart, fractionalPart),
// We allow a leading sign "-500.45", and a decimal point
NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint,
// We use a neutral culture in which the decimal separator is a dot (.)
CultureInfo.InvariantCulture);
如果字符串是用户输入,则应使用TryParse
代替并处理因用户输入错误而失败的情况:
decimal result;
if (!Decimal.Parse(
String.Format("{0}.{1}", integerPart, fractionalPart),
NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture,
out result))
{
// Handle invalid user input.
}
答案 4 :(得分:-1)
您也可以使用string.Join()
方法来完成此任务
string txt1, txt2;
txt1 = "500";
txt2 = "45";
var valueJoin = Convert.ToDecimal(string.Join(".", txt1,txt2));
Output 500.45