Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert double to 'long double' as standard

Tags:

c++

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;
like image 278
Nayana Adassuriya Avatar asked Mar 02 '15 07:03

Nayana Adassuriya


People also ask

How do you convert double to long?

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.


3 Answers

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.

like image 188
rici Avatar answered Sep 28 '22 16:09

rici


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.

like image 31
Rob Avatar answered Oct 02 '22 16:10

Rob


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").

like image 32
Eugene Malashkin Avatar answered Sep 29 '22 16:09

Eugene Malashkin