Number conversion

  • Thread starter Thread starter Nick Weekes
  • Start date Start date
N

Nick Weekes

Im just curious as to why the following applies to conversions of
Double/Float to integers (taken from MS docs):

"When you convert from a double or float value to an integral type, the
value is rounded towards zero to the nearest integral value"

Doesn't this produce inaccurate values, i.e. 2.9 becomes 2? Why
weren't other rounding rules applied?

Just a thought...
 
Nick said:
Im just curious as to why the following applies to conversions of
Double/Float to integers (taken from MS docs):

"When you convert from a double or float value to an integral type, the
value is rounded towards zero to the nearest integral value"

Doesn't this produce inaccurate values, i.e. 2.9 becomes 2? Why
weren't other rounding rules applied?

Just a thought...
Depends what you mean by "inaccurate". The conversion from float to integer is
normally defined to be "taking the integer part" rather than "rounding to the
nearest integer", or at least that is a useful way to think of it. If you know
you are working with positive values the usual primitive trick to accomplish
rounding before integerization would be something like:
integervariable = (int)(floatvariable + 0.5);
.. . . but it gets messier if negative values are involved.

Anyhow, rounding and integerization are separate steps and usually there is a
general-purpose rounding function available. In c# it appears to be Math.Round,
so you would do, e.g.:

integervariable = (int)(Math.Round(floatvariable, 0));

.. . . where the "0" indicates that you want the nearest integer, 1 would
indicate the nearest tenth, etc.

HTH,
-rick-
 
Back
Top