Reputation: 5760
Is there a built in routine in Java that will convert a percentage to a number for example, if the string contains 100% or 100px or 100, I want a float containing 100.
Using Float.parseInt or Float.valueOf result in an exception. I can write a routine that will parse the string and return the number, but I'm asking does this already exist?
Upvotes: 5
Views: 4835
Reputation: 7844
Your comment on this answer indicates that you need to support the string ending in "%", "px", or nothing at all. If the only content of the string is the number and the unit, than you should be able to get away with:
float floatValue = new DecimalFormat("0.0").parse(stringInput).floatValue();
If your number is surrounded by other jibberish inside of the string, and you only desire the first number that occurs, than you can utilize ParsePosition
:
String stringInput = "Some jibberish 100px more jibberish.";
int i = 0;
while (!Character.isDigit(stringInput.charAt(i))) i++;
float floatValue = new DecimalFormat("0.0").parse(stringInput, new ParsePosition(i)).floatValue();
Both of these solutions will give you the float value without requiring you to multiply the result by 100.
Upvotes: 1
Reputation: 5760
Thank you for the posts and suggestions, I did try using the solution posted by eg04lt3r, however the result was translated. In the end I wrote a simple function that does exactly what I require. I'm sure a good regular expression would have also worked.
public static double string2double(String strValue) {
double dblValue = 0;
if ( strValue != null ) {
String strResult = "";
for( int c=0; c<strValue.length(); c++ ) {
char chr = strValue.charAt(c);
if ( !(chr >= '0' && chr <= '9'
|| (c == 0 && (chr == '-' || chr == '+'))
|| (c > 0 && chr == '.')) ) {
break;
}
strResult += chr;
}
dblValue = Double.parseDouble(strResult);
}
return dblValue;
}
Upvotes: 0
Reputation: 2610
I think you can use:
NumberFormat defaultFormat = NumberFormat.getPercentInstance()
Number value = defaultFormat.parse("100%");
Upvotes: 20
Reputation: 1123
Use a StringBuffer to remove the %
sign and then you can convert it.
if (percent.endsWith("%")) {
String number = new StringBuffer(percent).deleteCharAt(percent.length() - 1);
float f = Float.valueOf(number);
} else [Exception handling]
The approach above is nicer, but I figured I would fix my answer regarding the comment. You would have to make sure you are dealing with percent before removing a character.
Upvotes: 0