Solved

# Casting doubles to integer problem

Posted on 2003-11-23
478 Views
Hiya

I have a small problem when trying to cast a double precision number to an integer:

When I input a double number into my program (its a command line program) I want to immediatly multiply it by 100 and convert it to an integer.  The user should always be inputing numbers with no more than 2 decimal places as it will always be an amount of money.

Basically it usually works for most numbers, but certain numbers such as 19.99 gets converted to 1998 (or 1998.99999999999 when I output the multipled double).

I was just wondering if there was a simple fix for this.
0
Question by:antt
• 2
• 2

LVL 86

Expert Comment

ID: 9806260
The manipulation of floating point values is constrained by degrees of precision - they frequently therefore end up as approximations. For arbitrary precision, use the BigDecimal class:

String s = "19.99";
double d = Double.parseDouble(s);
System.out.println(s + " (parseDouble) -> " + d * 100);
BigDecimal bd = new BigDecimal(s);
d = bd.doubleValue();
System.out.println(s + " (BigDecimal) -> " + d);
0

LVL 15

Expert Comment

ID: 9806630
double d = Double.parseDouble("19.99");
int cents = Math.round( d * 100 );
0

LVL 15

Accepted Solution

JakobA earned 25 total points
ID: 9806636
Oops. it needs an explicit cast:
int cents = (int)Math.round( d * 100 );
0

Author Comment

ID: 9809882
dammit still doesnt work
0

Author Comment

ID: 9809896
oh wait yes it does

i cant count
0

## Featured Post

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…