Home » Android » java – how to format string to show two decimal places

java – how to format string to show two decimal places

Posted by: admin June 15, 2020 Leave a comment

Questions:

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

How to&Answers:

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

pieChart.setCenterText("$ " + String.format("%.2f", d));

Answer:

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! 🙂

Answer:

Try Like This

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

Answer:

You can use DecimalFormat.

import java.text.DecimalFormat; 
DecimalFormat money = new DecimalFormat ("$0.00");
System.out.println(money.format(dataCost));

Answer:

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.