11

I am facing a slight issue when trying to get two decimal places after pasring double to string and trying to format

  pieChart.setCenterText("$" + "" + ""  +String.format( "% 1$ .2f", Double.toString(dataCost),""));

can anyone help me improve the above line of code so that it can display to two decimal places? You will also notice that I am trying to leave a space between the dollar sign and the value

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Zidane
  • 1,696
  • 3
  • 21
  • 35

5 Answers5

17

You can use String.format("%.2f", d) , your double will be rounded automatically

pieChart.setCenterText("$ " + String.format("%.2f", d));
mdDroid
  • 3,135
  • 2
  • 22
  • 34
  • mdDroid thanks this one works without causing the app to crash – Zidane May 30 '16 at 14:26
  • @Zidane always welcome – mdDroid May 30 '16 at 14:49
  • double totalDistance = distance(Double.parseDouble(prefs.getString("last_lat", null)), Double.parseDouble(prefs.getString("last_lang", null)), location.getLatitude(), location.getLongitude()); Log.d("Distance====>", String.format("%.2f", totalDistance)); – Ashwin H Apr 04 '17 at 05:37
5

Following code might help you

double a = 1.234567;
double a = 2;
NumberFormat nf = new DecimalFormat("##.##");
System.out.println(nf.format(a));
System.out.println(nf.format(a));

and the output will be

1.23
2

it only show decimal places if needed, Enjoy! :)

Bhoomit_BB
  • 51
  • 2
0

Try Like This

 pieChart.setCenterText("$ " + String.format("%.2f", dataCost));
Abhishek Patel
  • 4,280
  • 1
  • 24
  • 38
0

You can use DecimalFormat.

import java.text.DecimalFormat; 
DecimalFormat money = new DecimalFormat ("$0.00");
System.out.println(money.format(dataCost));
Sarhad Salam
  • 428
  • 3
  • 12
0

Try this.

    float val = 1245.235645f;
    double ans = Double.parseDouble(new DecimalFormat("##.##").format(val));

    System.out.println(ans);

Note : ##.## means 2 digits will be displayed after the .(dot)

Package  : import java.text.DecimalFormat;

this should helps you.

Sathish Kumar J
  • 4,280
  • 1
  • 20
  • 48