• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Decimal places

 
Anna Hays
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

This might sound stupid. But can anyone tell me how to set 2 decimal places in a double/Double when I call toString? I need it for the price.

Thanks.
 
peter wooster
Ranch Hand
Posts: 1033
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Anna Kafei:
Hello,

This might sound stupid. But can anyone tell me how to set 2 decimal places in a double/Double when I call toString? I need it for the price.

Thanks.


You need to use DecimalFormat eg:
 
Vanessa Danin
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By way of illustration, here is a code example which uses the java.text.NumberFormat class and its format(double) method in an overridden toString() method. Hope this helps.

import java.text.*;

public class Foo{

public static void main(String args[]) {
Price price = new Price(1234.5678);
System.out.println(price);
}
}

class Price{
double myDouble;
public Price(double myDouble){
this.myDouble = myDouble;
}
public String toString(){
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(2);
num.setMinimumFractionDigits(2);
String numStr = num.format(myDouble);
return numStr;
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic