2

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?

Dhiral Kaniya
  • 1,941
  • 1
  • 19
  • 32
PV_PN
  • 103
  • 2
  • 7
  • First you'll want to convert `percValue` to a `Double`, multiple it by 100, and then you can use something like `String.format()` to ensure that the resulting value only shows 2 decimal places. You can read more about string formatting here: https://dzone.com/articles/java-string-format-examples – Flaom Jun 17 '20 at 20:55
  • Does this answer your question? [How to escape % in String.Format?](https://stackoverflow.com/questions/5011932/how-to-escape-in-string-format) – andrewJames Jun 17 '20 at 21:20

4 Answers4

6

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.
Dhiral Kaniya
  • 1,941
  • 1
  • 19
  • 32
Ben Gillett
  • 376
  • 1
  • 9
1

You should parse the String into a double, multiply by 100, and then append the % sign to it as follows:

String percValue = "0.0209";
double per = Double.parseDouble(percValue);
String percentage = (per*100)+"%";
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
0

You need to parse your string value and then multiply by 100, something like this:

 String percValue = "0.0209";
 double value = ( Double.parseDouble(percValue)) * 100;
 String formatedValue = value + "%";
Bahij.Mik
  • 1,358
  • 2
  • 9
  • 22
0

Convert String to BigDecimal(for Big numbers) and multiply by 100.

String percValue = "0.0209";
BigDecimal temp=new BigDecimal(percValue).multiply(BigDecimal.valueOf(100)).stripTrailingZeros();

String formatedValue =temp.toString() + "%";