Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert double to float in Java

I am facing an issue related to converting double to float. Actually, I store a float type, 23423424666767, in a database, but when we get data from the database in the below code, getInfoValueNumeric(), it's of double type. The value we get is in the 2.3423424666767E13 form.

So how do we get a float format data like 23423424666767?

2.3423424666767E13 to 23423424666767

public void setInfoValueNumeric(java.lang.Double value) {     setValue(4, value); }   @javax.persistence.Column(name = "InfoValueNumeric", precision = 53) public java.lang.Double getInfoValueNumeric() {     return (java.lang.Double) getValue(4); } 
like image 794
Sitansu Avatar asked Sep 29 '15 07:09

Sitansu


People also ask

Can we convert double into float in Java?

floatValue() to Convert Double to Float in Java. Another way to convert a double value into a float data type in Java is by using the wrapper class Double. This class wraps a primitive data type double in an object.

What is possible lossy conversion from double to float?

As float can have decimal values that don't have corresponding long value. Therefore, we'll receive the same error. The double values can be too large or too small for an int and decimal values will get lost in the conversion. Hence, it is a potential lossy conversion.


2 Answers

Just cast your double to a float.

double d = getInfoValueNumeric(); float f = (float)d; 

Also notice that the primitive types can NOT store an infinite set of numbers:

float range: from 1.40129846432481707e-45 to 3.40282346638528860e+38 double range: from 1.7e–308 to 1.7e+308 
like image 62
Tom Wellbrock Avatar answered Oct 08 '22 15:10

Tom Wellbrock


I suggest you to retrieve the value stored into the Database as BigDecimal type:

BigDecimal number = new BigDecimal("2.3423424666767E13");  int myInt = number.intValue(); double myDouble = number.doubleValue();  // your purpose float myFloat = number.floatValue(); 

BigDecimal provide you a lot of functionalities.

like image 21
antoniodvr Avatar answered Oct 08 '22 14:10

antoniodvr