Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Converting Float to Double while maintaining precision

In Kotlin 123.456 is a valid Double value, however, 123.456F.toDouble() results in 123.45600128173828 - presumably just the way precision is handled between the two.

I want to be able to convert freely between the two, specifically for cases like this:

123.456F -> 123.456 // Float to Double

123.456 -> 123.456F // Double to Float

How can I convert a float to a double in cases like this, and maintain precision?

like image 897
Matthew Layton Avatar asked May 14 '19 12:05

Matthew Layton


People also ask

Can you turn a float into a double?

The doubleValue() method of Java Float class returns a double value corresponding to this Float Object by widening the primitive values or in simple words by directly converting it to double via doubleValue() method .

Is double more precise than float?

double has 2x more precision than float. float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value. float has 7 decimal digits of precision.

Can we store long value in float?

From float to long you could lose all behind the floating point so there will be no implicit cast because normally you do not want to lose this information. You may well lose information going from long to float . That's the point of the question.

What is the difference between float and double?

A float has 7 decimal digits of precision and occupies 32 bits . A double is a 64-bit IEEE 754 double-precision floating-point number. 1 bit for the sign, 11 bits for the exponent, and 52 bits for the value. A double has 15 decimal digits of precision and occupies a total of 64 bits .


1 Answers

It's a big ugly, but you could convert your Float to a String and back out to a Double:

val myDouble: Double = 123.456f.toString().toDouble()
// 123.456d

You could always encapsulate this in an extension function:

fun Float.toExactDouble(): Double = 
    this.toString().toDouble()

val myDouble = 123.456f.toExactDouble()
like image 69
Todd Avatar answered Oct 21 '22 09:10

Todd