如何将字符串转换为int或小数? [英] How to convert a string to an int or decimal?

查看:198
本文介绍了如何将字符串转换为int或小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

Console.WriteLine("What is the price of the product?"); 
Decimal price = Decimal.Parse(Console.ReadLine());  

我将输入作为字符串作为整数或/和十进制数字并将其转换为变量。好吧,那是我的意图。输入的是产品的价格,可以有小数,也可以没有。我只输入整数,它可以工作,但是用小数点它会崩溃。我是新手,似乎无法找到答案。

I take a input as a string as either a int or/and decimal number and convert it to a variable. Or well, that is my intention. The input is a price of a product and it can have decimals or it cannot. I you only type in ints, it works, but with decimals it crashes. I'm new to this and I can't seem to find an answer.

推荐答案

使用 TryParse 以防止发生异常:

Use TryParse to prevent exception:

while (true)
{
     string input = Console.ReadLine();
     decimal result;
     if (decimal.TryParse(input, out result))
     {
          // do your work
          break;
     }
     else
     {
          Console.WriteLine("invalid value try again");
     }
}

我在使用的同时循环强制用户输入正确的值。如果不希望它,则可以忽略该循环。

Also I have used while loop to force user to enter correct value.If you don't want it you can ignore the loop.

这篇关于如何将字符串转换为int或小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆