• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 407
  • Last Modified:

How do you convert a string value "0.0" to int?

Two questions....

1. How do I convert this to a int/whole number, in C#?
2. How do I truncate the .0 on the end? Anything to the right of the decimal I want removed?

sValue = "0.0";

Thanks.
0
mlong219
Asked:
mlong219
  • 2
  • 2
  • 2
  • +2
2 Solutions
 
Rajkumar GsSoftware EngineerCommented:
int num = (int) 0.0;
// num = 0
 
int num2 = (int)12.2434234;
 // num2 = 12
0
 
mlong219Author Commented:

@RajkumarGS:

I just tried this and I get the error: CS0030: Cannot convert type 'string' to 'int'

int iTotalReports = (int) sTotalReports;

I have a string variable with a value of "0.0", that I need to convert to int, and also get rid of the decimal place.
0
 
mlong219Author Commented:

I got it working by doing the following....

string sTotalReports = "0.0";
int iTotalReports = Convert.ToInt32(Convert.ToDecimal(sTotalReports));

I would think there is a better way.

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Rajkumar GsSoftware EngineerCommented:
You can use Math.Floor function
   
     string strTax = "23.67";
        decimal decTax = Math.Floor(Convert.ToDecimal( strTax));
        // Result = 23

Open in new window

0
 
Carlos VillegasFull Stack .NET DeveloperCommented:
I like this:
string sTotalReports = "0.0";
int iTotalReports = decimal.ToInt32(decimal.Parse(sTotalReports));

Open in new window

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
I would use Decimal.TryParse(), followed by Math.Truncate(), and then cast it to an (int).
0
 
informaniacCommented:
Isn't there something called abs in C#? Or it shd be Math.Abs. Not sure if anything like this exists.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
There is...but Math.Abs() just gives you the absolute value of a number (not the integral part).
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now