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;
There are a couple of ways to convert a double value to a long value in Java e.g. you can simply cast a double value to long or you can wrap a double value into a Double object and call it's longValue() method, or using Math. round() method to round floating-point value to the nearest integer.
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.
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.
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").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With