Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to format string to show two decimal places [duplicate]

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

like image 597
Zidane Avatar asked May 30 '16 11:05

Zidane


People also ask

How do I format a string to two decimal places?

String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you double only show two decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.

How do you show float up to 2 decimal places?

The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).

How do I format a string to two decimal places in Python?

2️⃣ f-string An f-string is a string literal in Python that has the prefix ' f ' containing expressions inside curly braces. These expressions can be replaced with their values. Thus, you can use f'{value: . 2f}' to return a string representation of the number up to two decimal places.


1 Answers

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! :)

like image 151
Bhoomit_BB Avatar answered Oct 13 '22 01:10

Bhoomit_BB