Round DOWN of a number of double type

  • Thread starter Thread starter Curious
  • Start date Start date
C

Curious

I want to get the integer part of a number declared as double type.
For instance, for 8.76, I want to get 8 instead of 9. In other words,
I want to cut off anything after the decimal point. Any advice on how
to do this?
 
Curious said:
I want to get the integer part of a number declared as double type.
For instance, for 8.76, I want to get 8 instead of 9. In other words,
I want to cut off anything after the decimal point. Any advice on how
to do this?

As you don't tell us what language, in general terms: cast it to an integer
type. That will truncate the decimal portion of the double.
 
As you don't tell us what language, in general terms: cast it to an integer
type. That will truncate the decimal portion of the double.

Thanks for the suggestion! FYI, I use C#.NET.
 
Curious said:
I want to get the integer part of a number declared as double type.
For instance, for 8.76, I want to get 8 instead of 9. In other words,
I want to cut off anything after the decimal point. Any advice on how
to do this?

What if it's negative?

Anyway, Math.Truncate does what you appear to want.

Andrew
 
What if it's negative?

Anyway, Math.Truncate does what you appear to want.

Andrew

I did a little experiment. a cast from double to int works fine for
both positive and negative numbers. It simply drops the residuals
after the decimal point.

However, if I use Math.Truncate, it gives me a runtime error, "Cannot
implicitly convert type 'double' to 'int'". FYI, the way I use it is
below:

double a = 8.9;
int correct1;
correct1 = Math.Truncate(a);

mLogSw.WriteLine(correct1.ToString());


double j = -4.3;
int correct2;
correct2 = Math.Truncate(j);

mLogSw.WriteLine(correct2.ToString());

double k = -8.7;
int correct3;
correct3 = Math.Truncate(k);
mLogSw.WriteLine(correct3.ToString());
 
I did a little experiment. a cast from double to int works fine for
both positive and negative numbers. It simply drops the residuals
after the decimal point.

However, if I use Math.Truncate, it gives me a runtime error, "Cannot
implicitly convert type 'double' to 'int'".

I suggest you use the method you've found to work.

(You didn't mention in your original post that you wanted to get the integer
part into an integer variable.)

If you check the help for the return type of the Math.Truncate method you'll
see why you got the runtime error, however; although I know nothing of C#, I
suspect the resolution to getting the result of Math.Truncate to be an Int
would make using Math.Truncate redundant.

HTH,

Andrew
 
Back
Top