Working with float

• 01-26-2010, 11:08 PM
dardar
Working with float
i using a vector of floating points.
when i print the vector the numbers looks like 2.2064104561

how do i "chop" them to something like 2.206 or so?

thank you
• 01-26-2010, 11:16 PM
Lil_Aziz1
System.out.printf(); or System.out.format(); works great

Code:

```double x = 4.215312531235; System.out.printf("%.3f",x);```
Output:
Code:

`4.215`

EDIT: System.out.printf() or System.out.format() will round. If you want to floor it (meaning round down) , subtract 0.5 from the float var and then do the System.out.printf() or System.out.format().
• 01-27-2010, 07:58 AM
dardar
let me rephrase my problem.

I'm using the line
double ans = Math.random();

ans looks like 2.01656717611 (ugly....)
is there a way after I'm using the random method to "chop" the number to 2.01

the printing is not the issue. i need to work with "relativity" large numbers.
• 01-27-2010, 10:29 AM
Tolls
Why do you need to truncate them like that?
• 01-27-2010, 03:12 PM
dardar
because!
it's hard to explain why......it's part of an algirthm i'm using.

someone told me the Class Double has a method to do that but i cant find it.
• 01-27-2010, 03:40 PM
Tolls
They might mean BigDecimal. That allows you to faff with scales, which is what you want I think.
• 01-27-2010, 03:58 PM
StormyWaters
You could always do something like this...

Code:

```float fValue = 2.01656717611f; fValue =    ((int)(fValue * 100)) / 100f;```
• 01-27-2010, 04:11 PM
Tolls
Is accuracy important? Just asking, because of the inevitable limitations of floating points in representing decimal fractions.
• 01-27-2010, 09:29 PM
dardar
i dont care about accuracy at all.