Java code: Limiting float values to 2 points past decimal.

semisonic9

Gawd
Joined
May 2, 2005
Messages
769
I'm trying to figure out how to limit a float output to two points past the decimal.

Example Code said:
import java.util.Scanner;

public class Land {

public static void main(String[] args) {

int length, width;
float acreage;

Scanner keyboard = new Scanner(System.in);

System.out.println("Please enter the length, in feet, of the length of a piece of land.");
length = keyboard.nextInt();
System.out.println("Please enter the length, in feet, of the width of a piece of land.");
width = keyboard.nextInt();

acreage = (length * width) / 43560;
System.out.println("Your acreage is " + acreage);
}
}

And I need the acreage only to two decimal places. Having a devil of a time trying to figure out how to make that happen.

I also need to know how to have it round up or down, as appropriate, for situations handling money.
 
if i remember correctly, NumberFormat allows you to set the min and max amount of decimals when formatting a number

IE:

NumberFormat nf = NumberFormat.getInstance();
nf.setMaxFractionDigits(2);
nf.setMinFractionDigits(2);
System.out.println(nf.format(3.1415));

this will output '3.14'
 
You want printf. Here's some example code:
Code:
float value = 1234.56789f;
System.out.printf("%.2f", value);   // Prints "1234.57"

Incidentally, there's an expression in your code that's just begging for trouble:
Code:
acreage = (length * width) / 43560;

Since all values in the expression are integers, integer division (case 4) will be performed. You want floating-point division. So, either make length or width floats, or divide their product by "43560f", not "43560".
 
Last edited:
3 different ways to achieve the same result!

Using a NumberFormat object is probably the way you want to go if you just need to display the result and do not need to do a bunch of computations on it.
 
achieve it through when its displayed, don't get carried away trying to limit yourself to 2 decimal point precision math or some similar nonsense.
 
Incidentally, there's an expression in your code that's just begging for trouble:
Code:
acreage = (length * width) / 43560;

Since all values in the expression are integers, integer division (case 4) will be performed. You want floating-point division. So, either make length or width floats, or divide their product by "43560f", not "43560".

Nice catch.

Went with DecimalFormat class on this one. Thanks for the feedback!
 
Back
Top