Java "100%" on the number

Is there a program built into Java that, for example, converts a percentage to a number, if the string contains 100% or 100 pixels or 100, I want the float to contain 100.

Using Float.parseInt or Float.valueOf throws an exception. I can write a procedure that will parse a string and return a number, but I ask if it already exists?

+4
source share
4 answers

Thanks for the posts and suggestions, I tried to use the solution posted by eg04lt3r, however the result was translated. In the end, I wrote a simple function that does exactly what I need. I'm sure a good regex would also work.

    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;
    }
0

, :

NumberFormat defaultFormat = NumberFormat.getPercentInstance()
Number value = defaultFormat.parse("100%");
+18

StringBuffer %, .

if (percent.endsWith("%")) {
    String number = new StringBuffer(percent).deleteCharAt(percent.length() - 1);
    float f = Float.valueOf(number);
} else [Exception handling]

, , . , , .

+1

, , "%", "px" . - , :

float floatValue = new DecimalFormat("0.0").parse(stringInput).floatValue();

, , 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 a float value without requiring you to multiply the result by 100.

0
source

Source: https://habr.com/ru/post/1624978/


All Articles