# Decimals going too far

• February 19th, 2014, 09:54 PM
Elyril
Decimals going too far
I had to make a table showing different values for converting kg to lbs and I'm confused because when it compiles, some of the decimals show correctly and some of them show with several 0's added on with another number on the end. Please help, I've tried to do math.random, but I'm not sure how to tie it in with my program. Please help.
Code Java:

```//1 kg = 2.2 lbs public class kg_to_lbs { public static void main(String[] args) { //not sure if values are needed.. int kg = 1; double lbs = 2.20;   //Table title System.out.println(" Kilograms to Pounds");   //First line headings System.out.println(" Kilograms | Pounds "); //do-while loop do { System.out.println(" " + kg + " | " + (kg * lbs) + " "); kg++; } while (kg <= 199); //end loop } }```
and this is some of the results I get
Code Java:

``` 1 | 2.2 2 | 4.4 3 | 6.6000000000000005 4 | 8.8 5 | 11.0 6 | 13.200000000000001```
• February 19th, 2014, 10:43 PM
dicdic
Re: Decimals going too far
Quote:

show with several 0's added on with another number on the end.
There are many ways to get rid of that.

One way
Is to use DecimalFormat class.

Other way
or if your variable is in double type variable, just cast it to float when printing:
example:
Code java:

```double answer = 3 * 2.20; System.out.println((float) answer);```

I think float data type has only one decimals.

Other way
you can also use substring. Just convert you decimal result to
String and used substring, you can use the index of dot ( . )
as reference on how many decimals you want to get.

And there are other ways,
• February 19th, 2014, 10:58 PM
Elyril
Re: Decimals going too far
I put converted to float, but sadly, I was unable to get the decimals all the way down to 1 decimal point. And the DecimalFormat class won't work for me, might've been the way I was putting it though. Thanks anyway! :)
• February 19th, 2014, 11:05 PM
aprabhat
Re: Decimals going too far
`System.out.printf("%d | %.2f\n",kg,kg*lbs);`