0

I would like the result of this to return correct to 2 decimal places.
ie price = 4.35 ie weightGrams = 233

public double pricePerHundredGrams()
{
   return (price * 100) / weightGrams; 
} 

I would like the calculation to return as 1.86 not 1.86695279....

user3338137
  • 57
  • 1
  • 3
  • The answers to this question should help you. http://stackoverflow.com/questions/2808535/round-a-double-to-2-decimal-places – lex82 Feb 21 '14 at 17:45
  • 1
    You should probably round when presenting the result, since a `double` knows nothing about the number of "human readable decimals" it contains. – Joachim Isaksson Feb 21 '14 at 17:45

3 Answers3

3

Create a DecimalFormat object, and pass in the pattern to parse a double into a String, representing the value to 2 d.p.

Example

DecimalFormat decFormat = new DecimalFormat("#.##");

double val = 1.456;

String formatted = decFormat.format(val);

System.out.println(formatted);

// outputs 1.45
christopher
  • 24,892
  • 3
  • 50
  • 86
1

Use String#format

double val=1.456;
String s= String.format( "%.2f", val );
System.out.print(s);
Nambi
  • 11,454
  • 3
  • 34
  • 49
0

Rough but fast way:

double result = (price * 100) / weightGrams; 
return ((int) (result * 100)) / 100.0;
lucasnadalutti
  • 5,380
  • 1
  • 22
  • 44
  • 4
    If you return an integer, how is this correct to two decimal places? – christopher Feb 21 '14 at 17:46
  • result * 100 would be an integer, but since it is divided by 100 it would be a double with 2 decimal places. I'm a bit rusty in Java nowadays since it's been a long time I don't use it, so I'm not sure if you'd need do do a parseDouble before dividing or not. – lucasnadalutti Feb 21 '14 at 17:51
  • 1
    @lucasnadalutti 105/100 = 1, but 105/100.0 = 1.05 – Joachim Isaksson Feb 21 '14 at 17:51
  • As @JoachimIsaksson said, `int / int = int`. You should brush up and have a read about [Arithmetic Promotion](http://www.codemiles.com/java/arithmetic-promotion-t3487.html). – christopher Feb 21 '14 at 17:54
  • That's right, guys, sorry for that. Answer edited. – lucasnadalutti Feb 21 '14 at 17:58