Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does converting a float to a double and back to float give the same value in C++

Assume in the following code

float f1 = ...;
double d1 = static_cast<double>(f1);
float f2 = static_cast<float>(d1);

ASSERT( f1 == f2 );

the variable f1 is initialized to something which is not a NaN. Is the assertion then guaranteed to hold by the C++ standard?

like image 589
Toby Brull Avatar asked Mar 23 '15 17:03

Toby Brull


People also ask

Can you convert a float to a double in C?

You can't convert from float to double and except that float will have the same precision of double.

Can a float be converted to a double?

A simple solution that works well, is to parse the double from the string representation of the float: double val = Double. valueOf(String. valueOf(yourFloat));

Are double and float interchangeable?

Float and double are both widely used data types in programming that have the ability to store decimal or floating-point​ numbers. The only difference between them is the precision. A float is a 32-bit IEEE 754 single-precision floating-point number.

Is it better to use double or float?

Double is more precise than float and can store 64 bits, double of the number of bits float can store. Double is more precise and for storing large numbers, we prefer double over float.


1 Answers

Here are some clues but not the answer:

4.6 A prvalue of type float can be converted to a prvalue of type double. The value is unchanged. This conversion is called floating point promotion. ...

4.8 A prvalue of floating point type can be converted to a prvalue of another floating point type. If the source value can be exactly represented in the destination type, the result of the conversion is that exact representation. If the source value is between two adjacent destination values, the result of the conversion is an implementation-defined choice of either of those values.

like image 149
fukanchik Avatar answered Sep 21 '22 17:09

fukanchik