简体   繁体   中英

Integer.parseInt and string format with decimal number

i try to convert string value into int. THe string value contain a decimal number, but i don't manage to convert this value in int format.

I've write this code:

public static void main(final String[] args){

    System.out.println("Test");
    final String nombre = "3.0";
    int entier;
    entier=Integer.parseInt(nombre);
    try
    {
        System.out.println("result :" + Integer.parseInt(nombre));
    }
    catch(final NumberFormatException nfe){
        System.out.println("NumberFormatException: "+nfe.getMessage());
    }
}

I have no result. Thank in advance for your help :)

由于它是字符串中的浮点数,因此请使用Float.parseFloatDouble.parseDouble而不是Integer.parseInt

Your String is a Double and not Integer .

         try
         {
             System.out.println("result :" + Float.parseFloat(nombre));
              // OR
             System.out.println("result :" + Double.parseDouble(nombre));
         }

From your description I understood that you want to print an int. You can code it like this:

    public static void main(final String[] args) throws ParseException {
            NumberFormat formatter = NumberFormat.getInstance();
            formatter.setParseIntegerOnly(true);
            System.out.println("Test");
            final String nombre = "3.0";
            int entier;
            entier=formatter.parse(nombre).intValue();
            System.out.println("result :" + entier);
        }

NumberFormat will do the job

you can still use the same input. try

  System.out.println("result :" + new Double(nombre).intValue());

I'm not sure what you're trying to do here, but this is a working piece of your code:

public static void main(final String[] args){

    System.out.println("Test");
    final String nombre = "3.0";
    float entier;
    entier=Float.parseFloat(nombre);
    try
    {
        System.out.println("result :" + Float.parseFloat(nombre));
    }
    catch(final NumberFormatException nfe){
        System.out.println("NumberFormatException: "+nfe.getMessage());
    }
}

Bottomline: use Float.parseFloat or Double.parseDouble

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM