-1

Suppose that I have:

    double Nc= 7.6695805E-4;
    NumberFormat formatter = new DecimalFormat("0.00000000000");
    String string = formatter.format(Nc);
    System.out.println(string);

the output would be:

    0.00076695805

But it is place in string type variable! What i have to do is to convert it into double or float or long so that it should remain same as 0.00076695805 and so that i can use it for my calculation! what i have tried is:

    double Nc= 7.6695805E-4;
    NumberFormat formatter = new DecimalFormat("0.00000000000");
    String string = formatter.format(Nc);
    System.out.println(Double.parseDouble(string));

the output becomes:

    7.6695805E-4 //which is same as i gave

so what should be the solution!

Java Nerd
  • 958
  • 3
  • 19
  • 51
  • You may be confusing a double primitive with its String representation -- they are two completely different things, and one does not affect the other. The solution is to control the String representation of your double when you need to display it. – Hovercraft Full Of Eels Mar 07 '15 at 20:08
  • possible duplicate of [How to round a number to n decimal places in Java](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) – Philipp Wendler Mar 07 '15 at 20:46

2 Answers2

3

You may be confusing a double primitive with its String representation -- they are two completely different things, and one does not affect the other. The solution is to control the String representation of your double when you need to display it.

The solution is to use a double when you need to use double, but to print the formatted String, not the double obtained from the String. So not:

double Nc= 7.6695805E-4;
NumberFormat formatter = new DecimalFormat("0.00000000000");
String string = formatter.format(Nc);
System.out.println(Double.parseDouble(string));

Note that the double has no memory of the String that was created with it, nor should it as double != String.

So instead, do:

double nc= 7.6695805E-4; // variable names begin with lower-case
NumberFormat formatter = new DecimalFormat("0.00000000000");
String string = formatter.format(nc);
System.out.println(string);

or

double nc= 7.6695805E-4; // variable names begin with lower-case
NumberFormat formatter = new DecimalFormat("0.00000000000");
System.out.println(formatter.format(nc));
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
1

use BigDecimal. 1 java doc

BigDecimal bd = new BigDecimal("String")
user3644708
  • 2,466
  • 2
  • 16
  • 32