I've used these posts as reference:
After reading through the solutions to these question, I'm still having trouble rounding up to the hundredths place. Here are what I've tried along with their outputs:
BigDecimal
import java.math.BigDecimal;
import java.math.RoundingMode;
public class RaceCarThread extends Thread {
private static boolean raceNow = false;
private int iterations;
private double lapsCompleted;
private boolean crash;
private int nbrOfCrashes;
// Default constructor
public RaceCarThread() {
super();
}
// Constructor for custom name
public RaceCarThread(String name) {
super(name);
raceNow = true;
lapsCompleted = 0;
crash = false;
nbrOfCrashes = 0;
}
public void run() {
while (!(lapsCompleted >= 17)) {
double randomNum = Math.random();
BigDecimal bd = new BigDecimal(randomNum).setScale(2, RoundingMode.HALF_EVEN);
randomNum = bd.doubleValue();
lapsCompleted = lapsCompleted + randomNum;
System.out.println(lapsCompleted);
}
}
}
10.31
10.5
11.13
11.850000000000001
12.810000000000002
13.570000000000002
14.200000000000003
15.080000000000004
15.800000000000004
16.200000000000003
16.790000000000003
17.430000000000003
Math.round(randomNum*100d) / 100d
public class RaceCarThread extends Thread {
private static boolean raceNow = false;
private int iterations;
private double lapsCompleted;
private boolean crash;
private int nbrOfCrashes;
// Default constructor
public RaceCarThread() {
super();
}
// Constructor for custom name
public RaceCarThread(String name) {
super(name);
raceNow = true;
lapsCompleted = 0;
crash = false;
nbrOfCrashes = 0;
}
public void run() {
while (!(lapsCompleted >= 17)) {
double randomNum = Math.random();
lapsCompleted = lapsCompleted + (Math.round(randomNum * 100d) / 100d);
System.out.println(lapsCompleted);
}
}
}
11.020000000000003
11.730000000000004
12.720000000000004
13.430000000000003
13.930000000000003
14.020000000000003
14.300000000000002
15.210000000000003
15.250000000000002
15.500000000000002
16.32
17.080000000000002
I'm unable to use DecimalFormat
due to using the number in calculations.
Edit: The System.out.println(lapsCompleted)
is just for checking the values and will be removed once I fix the decimals