# Get Percentage of a String

Discussion in 'Spigot Plugin Development' started by FrostedSnowman, Apr 15, 2017.

1. ### FrostedSnowman Resource Staff

hey, im not sure how I can get a percentage of a string. ex:

Code (Text):

HelloMyNam

to get 50% of it, i would get only 'Hello' since 50% of 10 chars, would be 5 chars.

i've tried this, but it doesn't really work:

Code (Java):

String x = "----------";
double percentage = .5;
x.substring(0, ((int) percentage * 10) - 1) + ChatColor.GRAY + x.substring(((int) percentage * 10) - 1)

2. ### ramidzk

You can do
Code (Text):
x.substring(0, (x.length() + (x.length() % 2))/2)
The (x.length() + (x.length() % 2)) stand for when the length is odd to add 1 the the length.

3. ### FrostedSnowman Resource Staff

could you explain how that would get a percentage of a string? i'd like to learn as much as possible.

4. ### Trigary

That code gets half of the string.
For any percentage: (untested)
Code (Text):
String string = "test";
float percentage = 0.5f;
return string.substring (0, Math.round (percentage * string.length ()));

5. ### ramidzk

For a variable percentage you would need a method like this:

Code (Text):
public static String getOfPercentage(double percentage, String x) {
// This might throw an exception
int y = ((int) (1/percentage));
return x.substring(0, (x.length() + (x.length() % y))/y);
}

int y = ...: Gets the divisor when you did 1/y or whatever.
x.substring(0, int): Basic Java. String are immutable so you have to get a potion of it as a new instance.
the int for the second substring: Gets 1/y of the string and adds some when it is too small.

EDITED

• Like x 1
6. ### FrostedSnowman Resource Staff

didnt seem to work either.

basically, what im trying to get at is:

get 40% of a string, then get the other 60% of it

7. ### FrostedSnowman Resource Staff

thanks, ill try it out, now.

8. ### ramidzk

I just edit it because 1. it was a void (facepalm) and 2. int y = (double) why??? (facepalm 2)

9. ### FrostedSnowman Resource Staff

got an arithemtic exception from using your provided method.

@ ArithmeticException: / by zero

10. ### ramidzk

You need to do something like (1D/a number) because java thinks 1 should be an integer

11. ### Trigary

ramidzk's way is probably better, but here's (another) straight forward approach:
Code (Text):
String string = "1234567";
float percentage = 0.4f;
int intValue = Math.round (string.length () * percentage);
Bukkit.broadcastMessage (string.substring (0, intValue) + "  " + string.substring (intValue));

12. ### FrostedSnowman Resource Staff

thanks, that works!

but, im going to mess around with the other way too