• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 442
  • 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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
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
 
Obadiah ChristopherCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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