2

In this program I'm printing a value from a calculation of type double to the screen.But at present the calculation is giving 14 decimal places.My question is,is there a facility in Java to wrap the output statement in that could specify the amount of decimal places?For example round(mark1,2)

enter image description here

The way it is printed at present is like this:

 double markOne = intent.getDoubleExtra("number1", 0);
 result1.setText(String.valueOf(markOne)+"mm");

Is it possible to wrap the setText in a Java method or would I have to create a custom format?Could someone give me an example of this with my code? Thanks

Brian J
  • 5,416
  • 19
  • 94
  • 189

3 Answers3

9

You could use a decimal formatter

DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
Amir Afghani
  • 35,568
  • 16
  • 81
  • 120
  • thanks,I'm just going to test now like this: `DecimalFormat df = new DecimalFormat("#.##"); result1.setText(String.valueOf(df.format(markOne)+"mm"));` – Brian J Dec 17 '13 at 17:50
  • That worked a charm,I was getting a lot of suggestions for convoluted custom methods earlier,when all I had to do was use `DecimalFormat` – Brian J Dec 17 '13 at 17:55
2

I think it's better to use BigDecimal type instead of Double. You could do

BigDecimal myValue= new BigDecimal(12.3577);
  myValue= myValue.setScale(2, BigDecimal.ROUND_HALF_UP);

And myValue will be 12.36

I hope this will help

Pracede
  • 3,890
  • 14
  • 54
  • 101
0

Try this:

  int decimalPlaces = 2;
    markOne = double(int(markOne*Math.pow(10, decimalPlaces)))/Math.pow(10, decimalPlaces);
Nikola Despotoski
  • 46,951
  • 13
  • 114
  • 146
Karasu
  • 101
  • 1