4

If I have

(float)value = 10.50

and do

int new_value = (int)value

what rules will round number?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
therainycat
  • 324
  • 1
  • 2
  • 14

3 Answers3

8

When a finite value of floating type is converted to an integer type, the fractional part is discarded (i.e., the value is truncated toward zero).

So in the case of -10.5, it's converted to -10.

C++11 4.9 Floating-integral conversions [conv.fpint]

An rvalue of a floating point type can be converted to an rvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type. [ Note: If the destination type is bool, see 4.12. —end note ]

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • Although it is in the quote you mention, I would explicitly [mention that this can overflow](http://stackoverflow.com/a/24348037/1708801) and recommend `round` or something similar instead. – Shafik Yaghmour Jul 01 '14 at 19:08
3

The rule is quite simple: the number simply gets truncated to its integral part, in this case, to 10. The fractional part gets dropped entirely. The same applies to negative numbers: -10.5 would be converted to -10.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • I tried something, and found, that float -20.50 will be -21 in integer - I guess, it's not so simple as truncating... Or I, as usual, doing wrong :) – therainycat Sep 29 '13 at 14:49
  • @therainycat Interesting. What platform are you on? That behaviour looks strange to me. I would expect to get `-20`. – juanchopanza Sep 29 '13 at 14:55
  • I write on PAWN, and sometimes work with files, made by C++. There's no construction as (int) in PAWN, so someone made include, in which (inc) just replaced to floatround(value, floatround_floor). So, I had bad values for numbers below 0 – therainycat Sep 29 '13 at 15:07
  • @therainycat sorry, I have no idea what you are talking about or how that applies to your question. – juanchopanza Sep 29 '13 at 15:08
1

When converted to integers, the fractional part of the float is dropped, meaning the float 10.5 will be converted to the integer 10, and the float -10.5 will be converted to the integer -10.

guyzyl
  • 387
  • 5
  • 18