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);
}
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
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.
Convert Double to Float
public static Float convertToFloat(Double doubleValue) {
return doubleValue == null ? null : doubleValue.floatValue();
}
Convert double to Float
public static Float convertToFloat(double doubleValue) {
return (float) doubleValue;
}
This is a nice way to do it:
Double d = 0.5;
float f = d.floatValue();
if you have d as a primitive type just add one line:
double d = 0.5;
Double D = Double.valueOf(d);
float f = D.floatValue();
Converting from double to float will be a narrowing conversion. From the doc:
A narrowing primitive conversion may lose information about the
overall magnitude of a numeric value and may also lose precision and
range.
A narrowing primitive conversion from double to float is governed by
the IEEE 754 rounding rules (§4.2.4). This conversion can lose
precision, but also lose range, resulting in a float zero from a
nonzero double and a float infinity from a finite double. A double NaN
is converted to a float NaN and a double infinity is converted to the
same-signed float infinity.
So it is not a good idea. If you still want it you can do it like:
double d = 3.0;
float f = (float) d;
To answer your query on "How to convert 2.3423424666767E13 to
23423424666767"
You can use a decimal formatter for formatting decimal numbers.
double d = 2.3423424666767E13;
DecimalFormat decimalFormat = new DecimalFormat("#");
System.out.println(decimalFormat.format(d));
Output : 23423424666767
The problem is, your value cannot be stored accurately in single precision floating point type. Proof:
public class test{
public static void main(String[] args){
Float a = Float.valueOf("23423424666767");
System.out.printf("%f\n", a); //23423424135168,000000
System.out.println(a); //2.34234241E13
}
}
Another thing is: you don't get "2.3423424666767E13", it's just the visual representation of the number stored in memory. "How you print out" and "what is in memory" are two distinct things. Example above shows you how to print the number as float, which avoids scientific notation you were getting.
First of all, the fact that the value in the database is a float does not mean that it also fits in a Java float. Float is short for floating point, and floating point types of various precisions exist. Java types float and double are both floating point types of different precision. In a database both are called FLOAT. Since double has a higher precision than float, it probably is a better idea not to cast your value to a float, because you might lose precision.
You might also use BigDecimal, which represent an arbitrary-precision number.
Use dataType casting. For example:
// converting from double to float:
double someValue;
// cast someValue to float!
float newValue = (float)someValue;
Cheers!
Note:
Integers are whole numbers, e.g. 10, 400, or -5.
Floating point numbers (floats) have decimal points and decimal places, for example 12.5, and 56.7786543.
Doubles are a specific type of floating point number that have greater precision than standard floating point numbers (meaning that they are accurate to a greater number of decimal places).
Float.parseFloat(String.valueOf(your_number)
Related
All integer literals are treated as int in java and floating point literals are treated as double in java.
Then why does
byte b =10;
does not give any error but
float f = 10.0;
gives a loss of precision error when in both cases down-casting takes place?
In the case of int to byte, there's no real concern about a loss of precision, because both types have the same degree of granularity. You'll get an error if you try to convert a literal with a value outside the range of byte to byte. (The error message given in that case is slightly misleading.)
In the case of double to float, you can have a constant value which is in the right range, but still lose precision. In your specific case of 10.0, the value can be represented exactly in both float and double, but that's not the case in general.
As an example of that, consider this:
float f = (float) 10.1; // Or float f = 10.1f;
double d = 10.1;
System.out.println(f == d); // Prints false
That's because precision is being lost in the conversion from double tofloat - neither type can represent 10.1 exactly, but double gets close to it than float does. The == operator will mean f is converted back to a double, with a different value to d.
float f = 0.00f;
System.out.println(f);
gives the output:
0.00
I'd like to format a number represented by a percentage to 2 decimal places. But the result should be a float and not a string.
e.g.
10.001 needs to be converted to 10.00
0.0 needs to be converted to 0.00
78.8 needs to be converted to 78.80
The values thus formatted will be assigned to a float.. how would one accomplish this?
private float parse(float val){
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Float.valueOf(twoDForm.format(val));
}
As long as you call it passing an valid float, your result will be a float.
But you can't show the right most zero if its not a String.
In the general case, you can't do that. There's no guarantee that a particular decimal value can be represented by a float that has only two digits right of the decimal.
A float is the wrong data type for this kind of precision. You need to use a decimal type or a scaled integer instead.
Assignment works the same way. If you assign the value 133.47 to a floating-point variable, your environment will assign the closest valid floating-point number to the variable. The closest valid floating-point number will probably not be 133.47.
You can compile and execute this program in C.
#include <stdio.h>
int main (void) {
float r;
r = 133.47;
printf("%.2f, %f\n", r, r);
return 0;
}
It prints these values on my system
$ ./a.out
133.47, 133.470001
Formatting to two decimal places changed the way 'r' looks, but it didn't change its value. Your system will do floating-point arithmetic based on the actual value, not the formatted value. (Unless you also change the data type.)
Floats don't have decimal places. They have binary places. It follows that the only fractions that can be represented exactly in a float to two decimal places are 0, 0.25, 0.5, 0.75. In all the other cases what you are asking is impossible.
import java.text.DecimalFormat;
public class Padding {
public static void main(String[] args) {
float value = 10.001f;
DecimalFormat decimal = new DecimalFormat("0.00");
String formattedValue = decimal.format(value);
System.out.println(formattedValue);
}
}
Output : 10.00
I don't understand why are float values different from double values. From the example bellow it appears that float provides different result than double for the same operation:
public class Test {
public static void main(String[] args) {
double a = 99999.8d;
double b = 99999.65d;
System.out.println(a + b);
float a2 = 99999.8f;
float b2 = 99999.65f;
System.out.println(a2 + b2);
}
}
Output:
199999.45
199999.44
Can you explain what makes this difference between float and double?
A float is a 32 bit IEEE 754 floating point.
A double is a 64 bit IEEE 754 floating point.
so it is just a matter of precision because neither of the fraction portions .8 and .65 have a terminating binary representation, so there is some rounding error. the double has more precision so it has slightly less rounding error.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Can you explain what makes this difference between float and double?
Sure. Imagine you had two decimal types, one with five significant digits, and one with ten.
What value would you use to represent pi for each of those types? In both cases you'd be trying to get as close to a number which you couldn't represent exactly - but you wouldn't end up with the same value, would you?
It's the same for float and double - both are binary floating point types, but double has more precision than float.
public class Main {
public static void main(String[] args) {
float a=12.6664287277627762f;
double b=12.6664287277627762;
System.out.println(a);
System.out.println(b);
}
}
Output:
12.666429
12.666428727762776
float can handle about 7 decimal places. A double can handle about 16 decimal places.
Doubles have twice the precision of floats. Thus they have smaller rounding errors.
A float has (usually) 32 bits, and a double 64 (again usually). Thus floats have rounding errors on more numbers than doubles.
Floats have less precision than doubles.
It's roughly half as much - 23 bits vs 52 for double(Thanks a lot Mr. Skeet!)!
32-bit for floats, 64-bit for doubles. ...Remember that the word "float" has fewer letters than "double", that's a "memory" trick :)
I'm searching for the best practice to convert Float to Double without loosing precision. So far I only found that a proper way to do so is to convert the Float to String and the String to Double.
Searching the Float API I stumbled upon this method doubleValue(). I thought this is a static constructor that will return a double from my Float without loosing precision but the following code behaves like a cast:
public class Main {
public static void main(String[] args) {
Float floatNumber= 4.95f;
Double doubleNumber= floatNumber.doubleValue();
System.out.println(doubleNumber);
}
}
The output is 4.949999809265137
Searching any other documentation about this from the Float API I didn't find any documentation to tell me what exactly happens when I call that method. Does anybody have any idea? Or can someone confirm that all the method does is perform a cast my Float to a double and unbox it?
The simple primitive-type cast (or even an implicit conversion) will do all you need, if you really want to preserve the value of a float:
float f = 4.95f;
double d = f;
Fundamentally 4.95f is already inaccurate - you can't represent that number exactly as a float. The exact value of floatNumber is represented in doubleNumber too - it's just that that value is not 4.95.
If you really care about the exact decimal digits, you should be using BigDecimal instead (or a scaled integer).
Widening float to double conversion doesn't lose precision in java.
When you use floating point, you get rounding errors which can be potentially "corrected" by rounding the result (assuming you know the precision you want). BigDecimal handles this by always knowing the precision.
float floatNumber= 4.95f;
double doubleNumber = (double) floatNumber;
System.out.println("After cast " + doubleNumber);
System.out.printf("Show two decimal places. %.2f%n", doubleNumber);
doubleNumber = Math.round(doubleNumber * 100) / 100.0;
System.out.println("After rounding to two places " + doubleNumber);
prints
After cast 4.949999809265137
Show two decimal places. 4.95
After rounding to two places 4.95
i have an Integer value:
Integer value = 56472201;
Where the value could be positive or negative.
When I divide the value by 1000000, I want this result in the form 56.472201 but instead it gives me just the quotient. How am I able to get both the quotient and remainder values?
cast it to float and then do it:
int i = 56472201;
float j = ((float) i)/1000000.0
Edit: Due to precision(needed in your case), use double. Also as pointed by Konrad Rudolph, no need for explicit casting:
double j = i / 1000000.0;
You have to convert the value to a floating point type first, otherwise you will be doing an integer division.
Example in C#:
int value = 56472201;
double decimalValue = (double)value / 1000000.0;
(The cast is actually not needed in this code, as dividing by a floating point number will cast the value to match, but it's clearer to write out the cast in the code as that is what actually happens.)
If you divide an int by a double you will be left with a double result as illustrated by this unit test.
#Test
public void testIntToDouble() throws Exception {
final int x = 56472201;
Assert.assertEquals(56.472201, x / 1e6d);
}
1e6d is 1 * 10^6 represented as a double