Float.parseFloat(java.lang.String) adds decimal numbers - java

I'm consuming a REST service and I get a value like "0.15" . I need to store it a float variable so, for the conversion, I use:
Float.parseFloat(value); //value = "0.15"
However, the returned values is not a strict 0.15 float but instead I get 0.150000005960464 . Any idea why I'm getting this?
If i receive the value without any decimals (10 for instance) this doesn't happen.

If you really require parsing the value "0.15" as something that exactly represents the real value 0.15, then you need to use BigDecimal (http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html):
BigDecimal parsed = new BigDecimal(value)
Your "10" is also not exactly 10, BTW.

I don't know if you can do something like this in android too, but I find this solution looking around:
NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
float b = Float.parseFloat( df.format(a));
Or maybe you can try to round the number
float b = Math.round(a * 100)/100.0f;

This happens because Float numbers cannot be represented exactly on a system.
A Floating Point number is represented on 32bit Architecture using this format.
http://en.wikipedia.org/wiki/Single-precision_floating-point_format
While on a 64bit architechture using this format.
http://en.wikipedia.org/wiki/Double-precision_floating-point_format
Representation of the number in the above two format results in loss of precision. Thus a number such as 0.15 can come up weirdly as 0.149999999998.
When you convert 0.15 to it's binary representation it gives you a recurring number which is 0.0010011001100....
10 however has a binary representation which is not recurring hence can be exactly represented on the above two systems.
0.15 however has some it's bits removed so as to fit in the above architecture where the precision loss happens.
Check the exact mathematics on how to convert a floating point number to a binary which will better help you understand where the precision loss is happening.
http://sandbox.mc.edu/~bennet/cs110/flt/dtof.html

Hi i resolved your problem...You will use like this You can get your need...Definitely it will give only the 0.15 format only use this...I hope you will get your desired Answer..
String decim= "0.15456564564564";
String convert = String.format("%.2f", Double.valueOf(decim));
float v = Float.parseFloat(convert);
System.out.println(v);

Related

jFormatted text field is not formatting the double data correctely

I've a jFormmatedTextField which is displaying double data incorrectly.
the field is formatted like this ##,##0.00 , however when the value of this field is set using setValue its sometimes displaying something like 77.88899888 which it should not.
this problem is happening for example when when I multiply 20.38 x 20 but when I multiply 20.38 x 15 its displaying correct number.
I dont understand why is this happening.
the code is like this:
resultField.setValue(new Double(myResultField));
Generally for arithmetic precision operations, try to use BigDecimal instead of Double field. This takes care of rounding up data to the precision you need. You can see it for yourself with the below code :
Double a = 20.38
Double b = 20
println(a * b)
BigDecimal c = 20.38
BigDecimal d = 20
println(c * d)
However if you cant change the type of the Variable, then you can use decimal format to format the output to your desired format
String pattern = "##,##0.00";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
println(decimalFormat.format(c * d))
println(decimalFormat.format(a * b))
Coming to why Doubles behave this way, it comes down to the way numbers are represented internally. There are a few good blogs on how float/doubles loose number precision (float precision loss ) . Long story short, due to the way its represented in memory floats/doubles loose precision, but BigDecimal representation doesnt suffer from this loss. Here are a few links that have more info.
https://www.soa.org/news-and-publications/newsletters/compact/2014/may/com-2014-iss51/losing-my-precision-tips-for-handling-tricky-floating-point-arithmetic/ .
https://en.wikipedia.org/wiki/Loss_of_significance .
Hope this helps

Why Float return different value and how can i solve it, Java

I am using Float to saving value. But when i save it seven and more then value in Float its return me different format value for example..
Float f=1234567.98
then float return me in string
1.23457e+06
What means of this and how can i solve it. Kindly please help me about this
Thanks in Advance
It means one of two things. Either your preferred printing method only shows a certain number of digits by default, or you are requesting more precision than a Float offers. The wikipedia page for single precision floats says that you can expect 6-9 decimal digits will be represented accurately. So that's probably your problem. You should be able to solve it by using a Double to store your value and DecimalFormat to customize the output.
To format a decimal use:
http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
In this case the format you want is ###.##
An example of using this would be
float f = 123456.78f;
DecimalFormat format = new DecimalFormat("###.##');
String formatted = format.format(f);
Note that if you are using this for monetary calculations you should use BigDecimal instead. Floats are an efficient way of storing real numbers, but they can only represent so many. Here is an example of using BigDecimal:
BigDecimal bd = new BigDecimal(123456.78f);
bd = bd.add(3.4f);
bd = bd.divide(4.3f);//this division with floats may have returned an inexact answer
bd.setScale(2);//Makes sure we only care about 2 decimal places
String strValue = bd.toString();

Convert string to float without round off java

I want to convert longitude and latitude that I get as a string from my database. The string is correct, and when i try to convert it into double, it is also correct. However when i am convert the double or the string value (i have tried both) into a float value, the last decimal gets round off.
The value of the string or double is 59.858139
The convertion to float is 59.85814
I've tried everything, and this is one desperate example :)
private float ConvertToFloat(double d)
{
float f = 00.000000f;
f = (float) d;
return f;
}
You are aware that doubles have more precision than floats and that floats round off, right? This is expected behaviour. There is no sense in casting a double to a float in this case.
Here's something to get you thinking in the right direction...
Double.doubleToRawLongBits(long value);
Float.intBitsToFloat(int bits);
Doubles can't fit into int and they have to fit into long. It's really twice the size, even mediating bits with strings won't do any good here.
1. float has only 24 bits of precision, which will be insufficient to hold the number of digits in your latitude and longitude.
2. The rounding off is due to the size of the number. So use double if you require floating point, or use BigDecimal
We are starting with your decimal number 59.858139
Convert that number to binary: 111011.11011011101011101111111101011100011011000001000110100001000100...
I.e. the number is an infinite fraction in binary. It is not possible to represent it exactly. (In the same way that it is not possible to represent 1/3 exactly with decimal numbers)
Rewrite the number to some form of binary scientific notation:
10 ^ 101 * 1.1101111011011101011101111111101011100011011000001000110100001000100...
Remember that this is still in binary, so the 10 ^ 101 corresponds to 2 ^ 5 in decimal notation.
Now... A float value can store 23 bits in the mantissa. If we round it up using "round to nearest" rounding mode, we get:
10 ^ 101 * 1.11011110110111010111100
Which is equal to:
111011.110110111010111100
That is all the precision that can fit into the float data type. Now convert that back to decimal:
59.8581390380859375
Seems pretty close to 59.858139 actually... But that is just luck. What happens if we convert the second closest float value to binary instead?
111011.110110111010111011 = 59.858135223388671875
So basically the resolution is approximately 0.000004.
So all we can really know from the float value is that the number is something like: 59.858139 ± 0.000002
It could just as well be 59.858137 or 59.858141.
Since the last digit is rather uncertain, I am guessing that the printing code is smart enough to understand that the last digit falls outside the precision of a float value, and hence, the value is rounded to 59.85814.
By the way, if you (like me are) are too lazy to convert between binary and decimal fractions by hand, you can use this converter. If you want to read more about the details of the floating point system, the wikipedia page for floating point representation is a great resource.

Java division for double and float without E

I'm doing some large number divisions (long/long to double, and int/int to float).. But I bump, to a problem when the results include the "E". I know we can use NumberFormat to format when displaying, but that's not what I. Just want the result of the divisions to not involve the "E", i.e. just round it up to the closest float/double that fits in the space.
Anybody got an idea?
The internal representation of floating point number does not have a switch for E presence or not (check IEEE-754). So your float/double number is just number (not a number with E or without it).
The only place where you get E is when you print this value out. And while Java uses number formater for printing, so I don't see a point why you don't want to use it here.
System.out.println(new DecimalFormat("#.#####").format(doubleValue));
The general problem that double and float in binary format. It not always possible to convert decimal fraction to binary fraction. For example 0.2 decmal fraction have infinitely many digits in binary (double) format. So whe converted from bynary format to decimal string, it result something like "0.2000000001" what displayed with E. To solve this problem you can use BigDecimal class what contains number in decimal format, so no E problem - it can easy rounded to any decimal point by setScale method. Or you can sore double as is, an write it to output by String.format("My value are: %.3f", value) - i recommend this way.
If you just want round you value to decimal point you can use:
new BigDecimal(val).setScale(3, RoundingMode.HALF_EVEN).doubleValue()
But there no any garanty what this core return double with fine fraction numbers.

Arithmetic expression calculates 6.135157E-6 instead of zero

I have the below code somewhere in my app
float private myMethod(float c){
result = (float) (c+273.15);
}
When "c" gets the value something like -273.1455 the result is something very near to zero like 0.0044.
But when it gets the value -273.15 i get this instead of zero: 6.1035157E-6
Why does this happen?
The problem is that 273.15 is a double, not a float, and neither of them can represent 273.15 exactly. However, since they have different precision they will round actually store different numbers. When the addition is done the c is converted to a double which will be able store the float representation of 273.15. So now you have two doubles with almost the same value and the difference will be non zero.
To get "more predictable" result, use 273.15f to ensure you have floats through the calculations. That should solve this problem but what you need to do is to read up on binary floating point arithmetics and how that differs from decimal arithmetic that we are taught in school.
Wiki on floating point is a good place to start.
Floating point calculations in computers are not accurate. You should read something about floating point arithmetics to prevent such errors.
The problem is not with the value, but with the display to the user.
I'm assuming you are converting it into a String. The way this is done is detailed in http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Double.html#toString(double)
To Display a correct value use the NumberFormat class http://docs.oracle.com/javase/1.4.2/docs/api/java/text/NumberFormat.html
Example :
NumberFormat formater = NumberFormat.getNumberInstance()
formatter.setMaximumFractionDigits(4);
formater.format(myMethod(-273.15))
Now you should get 0.

Categories

Resources