Tried as below
String d=new String("12.00");
Double dble =new Double(d.valueOf(d));
System.out.println(dble);
Output: 12.0
But i want to get 12.00 precision
please let me know correct way without using format() method in string class
We can convert String to Double object through it's constructor too. Also if we want double primitive type, then we can use doubleValue() method on it. Note that this constructor has been deprecated in Java 9, preferred approach is to use parseDouble() or valueOf() methods.
The double data type is a 64-bit double-precision IEEE 754 floating-point number. It means that it gives 15-16 decimal digits precision.
The atof() function converts a character string to a double-precision floating-point value.
We can convert String to double in java using Double. parseDouble() method.
Use BigDecimal
Instead of a double:
String d = "12.00"; // No need for `new String("12.00")` here
BigDecimal decimal = new BigDecimal(d);
This works because BigDecimal
maintains a "precision," and the BigDecimal(String)
constructor sets that from the number of digits to the right of the .
, and uses it in toString
. So if you just dump it out with System.out.println(decimal);
, it prints out 12.00
.
Your problem is not a loss of precision, but the output format of your number and its number of decimals. You can use DecimalFormat
to solve your problem.
DecimalFormat formatter = new DecimalFormat("#0.00");
String d = new String("12.00");
Double dble = new Double(d.valueOf(d));
System.out.println(formatter.format(dble));
I will also add that you can use DecimalFormatSymbols
to choose which decimal separator to use. For example, a point :
DecimalFormatSymbols separator = new DecimalFormatSymbols();
separator.setDecimalSeparator('.');
Then, while declaring your DecimalFormat
:
DecimalFormat formatter = new DecimalFormat("#0.00", separator);
You have not lost any precision, 12.0 is exactly equal to 12.00. If you want to display or print it with 2 decimal places, use java.text.DecimalFormat
If you want to format output, use PrintStream#format(...):
System.out.format("%.2f%n", dble);
There %.2f
- two places after decimal point and %n
- newline character.
If you don't want to use PrintStream#format(...)
, use DecimalFormat#format(...)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With