Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Float round when converting it into integer

If I have

(float)value = 10.50

and do

int new_value = (int)value

what rules will round number?

like image 475
therainycat Avatar asked Dec 15 '22 05:12

therainycat


2 Answers

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 ]

like image 174
Yu Hao Avatar answered Dec 28 '22 05:12

Yu Hao


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.

like image 42
juanchopanza Avatar answered Dec 28 '22 06:12

juanchopanza