How to print a double with two decimals in Android?

ArcDare picture ArcDare · Nov 9, 2011 · Viewed 175k times · Source

Maybe this is a silly question, but I cannot guess how to solve it if it's not creating a method. Maybe there's a "natural way" to do it, like in C for example. Here's the problem:

I have a var:

double a;

And I want to show it only with 2 or 3 decimals. When I try to show it:

Text.setText("Value of a: " + String.valueOf(a));

It gives something like:

Value of a: 5.234966145

And i would want just

Value of a: 5.23

Without changing the real value of a so it shows the approximate number but works with the real number.

Answer

Goz picture Goz · Nov 9, 2011
yourTextView.setText(String.format("Value of a: %.2f", a));