Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an Integer.parseInt() for a decimal number?

The Java code is as follows:

String s = "0.01"; int i = Integer.parseInt(s); 

However this is throwing a NumberFormatException... What could be going wrong?

like image 748
Kevin Boyd Avatar asked Sep 20 '09 13:09

Kevin Boyd


People also ask

Does parseInt work with decimals?

parseInt will only parse the leading part of the string that defines a whole number ("int" = "integer" = "whole number"), so it stops at the , . parseFloat will parse a decimal number, but only understands . as the decimal point, not , , even in locales where , is the decimal point.

Can int take decimal values in Java?

Numbers are so important in Java that six of the eight primitive data types are numeric types. There are both integer and floating point primitive types. Integer types have no fractional part; floating point types have a fractional part. On paper, integers have no decimal point, and floating point types do.

What is the use of parseInt () to convert a string containing decimal value?

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .


1 Answers

String s = "0.01"; double d = Double.parseDouble(s); int i = (int) d; 

The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3 to a int is nonsense. A double or a float datatype can hold rational numbers.

The way Java casts a double to an int is done by removing the part after the decimal separator by rounding towards zero.

int i = (int) 0.9999; 

i will be zero.

like image 54
Martijn Courteaux Avatar answered Oct 04 '22 13:10

Martijn Courteaux