Converting string to float in Java without round it [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Rounding in java Float.parseFloat
I want to convert strings to float i say:
System.out.println(Float.parseFloat("1553781.9829"));
Output:
1553782.0
I say:
System.out.println(Float.valueOf("1553781.9829"));
Output:
1553782.0
How to get Float without lossing precision?

use System.out.println(Double.parseDouble("1553781.9829")); instead
float has a limitation of smaller size (4 bytes) so it's not good for big decimals, double has the double size (8 bytes)

If you are looking for accuracy, I would suggest BigDecimal
This is just like normal wrapper class which provides methods for all your operations. And yes it takes argument as String as well.
BigDecimal bd = new BigDecimal("1553781.9829");
System.out.println(" bd :"+ bd); //prints the same value
URL : http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html

You cannot use float or double without a risk of losing precision. First of all their precision is limited, for float it is approx 7-8 decimal digits, for double ~16 digits. Apart from that Java floating points types are binary internally so they cannot store some decimal fractions without losing precision. If you really need exact decimal fractions use java.math.BigDecimal. Read "Effective Java" Item 48: "Avoid float and double if exact answers are required".

Instead of Float you can use Double
System.out.println(Double.valueOf("1553781.9829"));
System.out.println(Double.parseDouble("1553781.9829"));

Related

How to get the value without round up/down in Java? [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
double d0 = Double.parseDouble("53.82233040000000557");
double d1 = Double.valueOf("53.82233040000000557");
output
d0 = 53.822330400000006
d1 = 53.822330400000006
Precision Numbers in Java
Class java.math.BigDecimal is better for handling numbers where precision matters (like monetary amounts), see BigDecimal VS double.
It could be used for geo-coordinates (latitude/longitude). Although practitionars argue that double is precise enough for lat./long. - since you don't want to locate something at nano-meter scale.
Example Code
If you need high precision and scale for your number, use BigDecimal like this:
BigDecimal decimalValue = new BigDecimal("53.82233040000000557");
System.out.println("as BigDecimal: " + decimalValue.toPlainString());
// prints exactly: 53.82233040000000557
Run this code online (IDE one): Double VS BigDecimal for high precision
Read more
Read more in a tutorial on Java: BigDecimal and BigInteger
If you need precision, you have to use a BigDecimal.
The answer is that you cannot. The values you are getting are the most accurate approximation to your values that can possibly be stored in a double. There is no possible way to get a more accurate, less rounded value stored in a double.
If you require that the answers are not rounded at all, therefore, you should not be using double. The data type you should be using instead is BigDecimal.

Formatting Double to String? [duplicate]

This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed 3 years ago.
String.format("%,.0f", 200000000000000000000000.0)
-> 199,999,999,999,999,980,000,000
why?
Understand the Double Data type - it is an approximation of amount and scale.
The Following assignment:
double d = 2.00000000000f;
will generate a value of 1.9999999 at times when printed. What you are seeing here is magnification of that. Double Data types also have a maximum (implementation-dependant) of how many places of significance they can support (upto 15 generally) - which is why the last 6 digits are all zeros (0)
For your particular solution, if you don't require Floating-point Data, stick to Integer.
It is because current processors(and most VMs) work like that if use default data types. Here it is explained in details
If you want precision use BigDecimal. This class is specifically intended for situations like this - to be used in currency related stuff and scientific calculations.
To format decimals in proper way Java has DecimalFormat
String pattern = "###,###.###";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
String format = decimalFormat.format(123456789.123);
System.out.println(format); // -> 123.456.789,123
Here is nice tutorial about it
Hope it helps.
My problem has been solved
String.format("%,.0f", BigDecimal( 200000000000000000000000.0, MathContext.DECIMAL64))

Problem with double value with Expansion in java , I was trying to add two double values but not giving accuracy [duplicate]

This question already has answers here:
Retain precision with double in Java
(24 answers)
Closed 4 years ago.
The given values are
double double1 = 1.0814449990040142E7;
double double2 = 7.0164302885665664E17;
result is double1 + double2 = 7.016430288674711E17 in Java
Manually calculated value is 701643028867471089
Can anyone resolve my issue.
Unfortunately, this is a case of There Ain't No Such Thing As A Free Lunch.
Double gets its performance by using a compact format. Every double occupies exactly 64 bits. That allows very efficient storage and transfers between processor and memory, the use of registers to hold double values, and hardware implementation of arithmetic. A BigDecimal is a data structure whose size depends on the value being represented, but can be much bigger than 64 bits.
The price you pay for double's efficiency is that it can exactly represent only a subset of the numbers that BigDecimal can represent exactly. The closest doubles to your literals are 10814449.9900401420891284942626953125 and 701643028856656640. Their exact sum is 701643028867471089.9900401420891284942626953125. It is not itself the exact value of any double. It is bracketed by the doubles 701643028867470976 and 701643028867471104, the closer of which is the result you got.
For many purposes, doubles are close enough. For example, if your variable represents a measured physical quantity, the measurement error will dwarf the rounding error on converting to double. The numbers that can be expressed as terminating decimal fractions are no more important than other rationals and irrationals. In those cases, use double and round outputs to the number of digits justified by the input precision and accumulated rounding error.
Other cases, such as some financial calculations, require exact arithmetic on decimal fractions. Less often, decimal fractions have no special significance, but you need more precision than double can give you. In both those cases, BigDecimal is the right data type despite the performance cost.
Double values are not accurate in Java, you should use the BigDecimal class, which has a lot better precision.
For more information refer to the documentation: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
just format it how you want
double double1 = 1.0814449990040142E7;
double double2 = 7.0164302885665664E17;
System.out.printf("%.2f", double1 + double2);
output 701643028867471100.00
or
System.out.printf("%.0f", double1 + double2);

Java String parseFloat or double for x.xxxxxx numbers?

I have numbers in String like:
"34.556231"
"43.385644"
"65.659388"
with six decimals after dot.
I want to parse them to Float or eventually Double.
How to convert these Strings to Float or Double?
When I use Float.parseFloat("5.586905") then the float value is equal 5.58691 so it looks like its parsing to only 5 decimal places and rounds it.
How to resolve it?
float doesn't have enough precision to store the number you are giving it. Use double instead.
As the java specs say,
As with the recommendations for byte and short, use a float (instead
of double) if you need to save memory in large arrays of floating
point numbers
In other words, don't use float unless storage is a major concern. It is much less precise than double and will lead to ridiculous results like the one you just outlined.
Use Double.parseDouble.
If you have more numbers after decimal then you can use bigdecimal like this
String x="5.586905";
BigDecimal b=new BigDecimal(x);
double value=b.doubleValue() ;
System.out.println(value);
but as per your given number Double.parseDouble() is enough

Show only two digit after decimal [duplicate]

This question already has answers here:
how to convert double to 2 number after the dot? [duplicate]
(6 answers)
Closed 9 years ago.
How to get the double value that is only two digit after decimal point.
for example
if
i=348842.
double i2=i/60000;
tv.setText(String.valueOf(i2));
this code generating 5.81403333.
But I want only 5.81.
So what shoud I do?
Use DecimalFormat.
DecimalFormat is a concrete subclass of NumberFormat that formats
decimal numbers. It has a variety of features designed to make it
possible to parse and format numbers in any locale, including support
for Western, Arabic, and Indic digits. It also supports different
kinds of numbers, including integers (123), fixed-point numbers
(123.4), scientific notation (1.23E4), percentages (12%), and currency
amounts ($123). All of these can be localized.
Code snippet -
double i2=i/60000;
tv.setText(new DecimalFormat("##.##").format(i2));
Output -
5.81
How about String.format("%.2f", i2)?
Here i will demonstrate you that how to make your decimal number short. Here i am going to make it short upto 4 value after decimal.
double value = 12.3457652133
value =Double.parseDouble(new DecimalFormat("##.####").format(value));
Many other answers only do formatting. This approach will return value instead of only print format.
double number1 = 10.123456;
double number2 = (int)(Math.round(number1 * 100))/100.0;
System.out.println(number2);
I think the best and simplest solution is (KISS):
double i = 348842;
double i2 = i/60000;
float k = (float) Math.round(i2 * 100) / 100;
i=348842.
double i2=i/60000;
DecimalFormat dtime = new DecimalFormat("#.##");
i2= Double.valueOf(dtime.format(time));
v.setText(String.valueOf(i2));
First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.
And other aspect is providing proper result. So you want to truncate the number or round it.
So before you start you should ask your self, am i interested on the value or not.
To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.

Categories

Resources