Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Decimal digits

 
Abder-Rahman Ali
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java, when I do this for example:

0.75 - 0.25

I get: 0.5

How can I get: 0.50

Thanks.
[ June 24, 2008: Message edited by: Abder-Rahman Ali ]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Realize that the answer, and how you display the answer, are two different things. Numbers don't have a certain number of digits; it's just how you display them that counts.

Use the java.text.DecimalFormat class, or use the System.out.printf() method. Both are well- described in their Javadocs.
 
vas reddy
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try this...
but final result is in String you need to convert that into double

import java.text.*;
public class Value {
public static void main(String args[])
{
double x = 0.75;
double y = 0.25;
double z = x-y;
System.out.println("z =" + z);

NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
String s = nf.format(z);

System.out.println("s =" + s);

}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic