Reputation: 599
I am new to android and java programming, so please forgive me if this is an easy question. My problem is to add % in end of the decimal value. I will get double value and don't know how much digits after decimal point, i need to convert to two digits after decimal point and finally need to add % at last position. The problem is, I will format the double value only once. I have tried like this DecimalFormat ("#.##%"), but decimal points moved two digits forward. Please help me to get out of this problem.
Using DecimalFormat ("#.##%"),
Actual : 34.142545
Output : 3414.25%
Upvotes: 0
Views: 272
Reputation: 124215
If you use %
in format, it means that you want to convert value to percentage, but you need to remember that value 1
in percentage world is equal to 100%
so value you use will be automatically multiplied by 100. To avoid this behaviour you can change %
into literal by quoting it with apostrophes '%'
new DecimalFormat("#.##'%'");
Upvotes: 1
Reputation: 169
By adding the % in the format, you multiply by 100 and add the % character. This is why it looks like the decimal point moves.
You can use something like:
String output = new DecimalFormat("#.##").format(input) + "%";
An alternative is to divide by 100 before formatting:
String output = new DecimalFormat("#.##%").format(input / 100.0);
Upvotes: 1