The moose likes Beginning Java and the fly likes Decimal digits Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Decimal digits" Watch "Decimal digits" New topic

Decimal digits

Abder-Rahman Ali
Ranch Hand

Joined: May 22, 2008
Posts: 138
In Java, when I do this for example:

0.75 - 0.25

I get: 0.5

How can I get: 0.50

[ June 24, 2008: Message edited by: Abder-Rahman Ali ]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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.

[Jess in Action][AskingGoodQuestions]
vas reddy

Joined: Jun 11, 2008
Posts: 23
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();
String s = nf.format(z);

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

I agree. Here's the link:
subject: Decimal digits
It's not a secret anymore!