简体   繁体   中英

Can't parse this int

I got a simple question, I got error when I do: I can't convert it to int...

string buy = "16.11";
int _buy = (int.Parse(buy) * 9);

Int stands for Integer. You can't parse delimited value to int. Change it to double or decimal. For example:

string buy = 16.11;
double _buy = double.Parse(buy) * 9;

Well, 16.11 is a float number , so you have to parse into, say, Double and the round up to int :

string buy = "16.11";
int _buy = (int)(Double.Parse(buy) * 9 + 0.5); // 0.5 for rounding up

if _buy is actually a float or decimal , treat it as being float or decimal

 string buy = "16.11";
 // We usually use Decimal for money
 Decimal _buy = Decimal.Parse(buy) * 9;

A string variable cannot hold a decimal value, your string initialization is also wrong, you can do like the following, a string should be within double quotes, or else you should add .ToString() :

string buy = "16.11";
int _buy = (int)(Double.Parse(buy) * 9 + 0.5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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