Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert a string to float and avoid using try/catch in java?

There are some situation that I need to convert string to float or some other numerical data-type but there is a probability of getting some nonconvertible values such as "-" or "/" and I can't verify all the values beforehand to remove them. and I want to avoid using try/catch for this matter , is there any other way of doing a proper conversion in java? something similar to C# TryParse?

like image 503
Seyed Vahid Hashemi Avatar asked Dec 02 '11 20:12

Seyed Vahid Hashemi


1 Answers

This is an old question, but since all the answers fail to mention this (and I wasn't aware of it myself until seeing it in a merge request written by a colleague), I want to point potential readers to the Guava Floats and Ints classes:

With the help of these classes, you can write code like this:

    Integer i = Ints.tryParse("10");
    Integer j = Ints.tryParse("invalid");
    Float f = Floats.tryParse("10.1");
    Float g = Floats.tryParse("invalid.value");

The result will be null if the value is an invalid int or float, and you can then handle it in any way you like. (Be careful to not just cast it to an int/float, since this will trigger a NullPointerException if the value is an invalid integer/floating point value.)

Note that these methods are marked as "beta", but they are quite useful anyway and we use them in production.

For reference, here are the Javadocs for these classes:

  • https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/primitives/Ints.html
  • https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/primitives/Floats.html
like image 111
Per Lundberg Avatar answered Oct 08 '22 10:10

Per Lundberg