Parsing float stored as string should throw Exception

前端 未结 1 1534
无人及你
无人及你 2021-01-17 17:19

I have a string which stores a number. Now i want to parse that string and get as float.

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name          


        
相关标签:
1条回答
  • 2021-01-17 18:15

    As you can see in the related source code, the value will be trimmed:

    static FloatingDecimal.ASCIIToBinaryConverter readJavaFormatString(String arg) throws NumberFormatException {
        boolean arg0 = false;
        boolean arg1 = false;
    
        try {
            arg = arg.trim();
         ....
    

    So the blanks will be removed before converting to a floatValue. For more informations see the sourcecode of FloatingDecimal which is called by Float.class.

    Integer.parseInt() do not trimm the string value:

    public static int parseInt(String arg, int arg0) throws NumberFormatException {
        if (arg == null) {
            throw new NumberFormatException("null");
        } else if (arg0 < 2) {
            throw new NumberFormatException("radix " + arg0 + " less than Character.MIN_RADIX");
        } else if (arg0 > 36) {
            throw new NumberFormatException("radix " + arg0 + " greater than Character.MAX_RADIX");
        } else {
            int arg1 = 0;
            boolean arg2 = false;
            int arg3 = 0;
            int arg4 = arg.length();
            int arg5 = -2147483647;
            if (arg4 > 0) {
                char arg8 = arg.charAt(0);
                if (arg8 < 48) {
                    if (arg8 == 45) {
                        arg2 = true;
                        arg5 = MIN_VALUE;
                    } else if (arg8 != 43) {
                        throw NumberFormatException.forInputString(arg);
                    }
    
                    if (arg4 == 1) {
                        throw NumberFormatException.forInputString(arg);
                    }
    
                    ++arg3;
                }
    
                int arg7;
                for (int arg6 = arg5 / arg0; arg3 < arg4; arg1 -= arg7) {
                    arg7 = Character.digit(arg.charAt(arg3++), arg0);
                    if (arg7 < 0) {
                        throw NumberFormatException.forInputString(arg);
                    }
    
                    if (arg1 < arg6) {
                        throw NumberFormatException.forInputString(arg);
                    }
    
                    arg1 *= arg0;
                    if (arg1 < arg5 + arg7) {
                        throw NumberFormatException.forInputString(arg);
                    }
                }
    
                return arg2 ? arg1 : -arg1;
            } else {
                throw NumberFormatException.forInputString(arg);
            }
        }
    }
    

    Thats why you get an Exception there

    0 讨论(0)
提交回复
热议问题