• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to convert to a exact double from float expression  RSS feed

 
jakeer ahmed
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi friends i hav fallowing class.


public class TestAction {

public static void main(String[] args) {
float val=0.4f;
int newval=-3;
double finval = val1 * Math.pow(10.0,newval);
System.out.println("finval1:"+finval1);
}
}

on execution finalval is 4.000000059604645E-4

But i require exact double value. here it is 4.0E-4.
can anyone help me
thanks alot
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is not an advanced question. It's pretty basic.

Floating-point (float or double) cannot represent every possible real number exactly. It is therefore impossible to obtain total accuracy in floating-point calculations.

If what you want is just to achieve a textual representation that doesn't have the random garbage in the least-significant digits, then you need to convert your floating-point values to text in a controlled way using something like the java.text.DecimalFormat class.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Indeed. Moving to Java in General (Beginner).
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Float and double NEVER represent an exact number in the mathematical sense, so what you ask is impossilbe. However, I think you mean that you want to display the number in a certain format. You should look at NumberFormat and its subclasses for methods that allow you to format numeric output.

Layne
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!