Reputation: 1667
I have to display digit in two decimal points.
Let say value 0 should display as 0.00 and value 2.3 shoule display as 2.30.
To achive this I have done something like below :
Log.e(">>> percent ", ">> " + data.percent)
percent = String.format("%.2f", percent).toDouble()
Log.e(">>> percent ", ">> " + percent)
But the result you will notice is as below :
2021-04-15 11:55:54.580 10061-15047/com.dev E/>>> percent: >> 0
2021-04-15 11:55:54.580 10061-15047/com.dev E/>>> percent: >> 0.0
It should be 0.00 instead of 0.0
What might be the issue? Please guide. Thanks.
Upvotes: 0
Views: 139
Reputation: 1789
just change
String.format("%.2f", percent).toDouble()
to
String.format("%.02f", data.percent)
Upvotes: 0
Reputation: 304
You can use DecimalFormat https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
val df = DecimalFormat("0.00")
df.format(percent)
Upvotes: 0
Reputation: 15552
Double
type does not have information about how to display.
So, do not use toDouble()
method to the string.
Also, add 0
to the format string to denote the zero padding.
Log.e(">>> percent ", ">> " + data.percent)
val percentStr: String = String.format("%.02f", data.percent)
Log.e(">>> percent ", ">> " + percentStr)
Upvotes: 2