Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String decimal to percentage in java [duplicate]

I have a string value as below:

String percValue = "0.0209"

How can I convert this to something like as below

String formatedValue = "2.09%";

Can someone help me what is the simple and best way to convert this?

like image 579
PV_PN Avatar asked Apr 07 '26 04:04

PV_PN


1 Answers

One good way would be to:

  • convert your percentage string to a number (needs to be a double type variable, so it can hold the decimal places...),
  • multiply the value by 100 to make it a percentage,
  • re-format the number in a string.
String percValue = "0.0209";
double percentage = Double.parseDouble(percValue) * 100;
String formattedValue = String.format("%.2f%%", percentage);

Explanation:

  • Double.parseDouble() takes your string as a parameter and returns a double value which you can do things like multiplication and addition with, and
  • String.format() lets you precisely control how your number is converted back to a String!
  • "%.2f" means "Take the next argument which is a floating-point variable and put it here, with two decimal places".
  • "%%" means "print a single '%'". You need two to "escape" it, since percent symbols are not literally interpreted in format strings.
like image 139
Ben Gillett Avatar answered Apr 09 '26 18:04

Ben Gillett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!