[Interest] how to convert double to int safely?

André Somers andre at familiesomers.nl
Tue Nov 25 09:46:10 CET 2014


nus1998 schreef op 25-11-2014 09:33:
> Hi All, I have some code like followed:
>
>     doubled=9.02;
>      d  /=  0.02;
>      int  i  =  static_cast<int>(d);
>      qDebug()  <<  d  <<  i;
>
> the result is 451 and 450, but I want  'i' be 451 too, how?
> thanks in advance
>
>
>
>
>
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> http://lists.qt-project.org/mailman/listinfo/interest
This is not a Qt issue, it is a general computer issue. Familiarize 
yourself with the basics of how floating point numbers work, the kinds 
of inprecision that occur, and the types of rounding that are available 
(round, floor, ceil). Casts are usually not the best way to deal with 
converting number types. They just disgard the non integer part of a 
number, even if in decimal that would be represented as .999999999999.

André

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20141125/b081c27d/attachment.html>


More information about the Interest mailing list