Reputation: 24756
How to convert double
to long double
as C++ standard. I think just casting like this is not the right way?
double value = 1.2;
long double newValue = (long double)value;
Upvotes: 5
Views: 10855
Reputation: 1974
The standards guarantee that a long double
can support all the values that a double
can (or, to put it another way, the set of values a double
can support is a subset of what a long double
can represent).
So, the assignment
long double newValue = value;
is sufficient, albeit involving an implicit conversion of value
from double
to long double
rather than an explicit conversion. It is a conversion that does not lose precision.
Explicit alternatives in C++ are
long double newValue = (long double)value; // as in original question
long double newvalue = static_cast<long double>(value);
It is really a matter of subjective style which alternative is considered better, because they all achieve the same effect without potential loss of precision.
Note that, if going the other way (converting from long double
to double
) it is often preferable to use an explicit conversion, since the conversion potentially loses precision (and can therefore change the value) - which is why compilers often (can be configured to) give warnings on such implicit conversions.
Upvotes: 4
Reputation: 161
Employ static_cast:
long double newValue = static_cast<long double>(value);
Or in C++11 style:
auto newValue = static_cast<long double>(value);
(known as "explicitly typed initializer idiom").
Upvotes: 2
Reputation: 241901
That will work fine, but it will not magically create extra precision in newValue
. That is, it will not produce the same result as:
long double newValue = 1.2L;
which will set newValue
to a closer approximation to 1.2.
Upvotes: 6