mercredi 28 février 2018

How to round a double to two decimals through Formatting, then using the number afterwards?

Im currently making a program that generates a random number and then calculates the amount of 20 dollar, 1 dollars, quarters, pennys etc it would take to make that number. This is what im using to calculate the double, with randomValue being the random double.

double rangeMin = 1;
double rangeMax = 100;
Random r = new Random();
double randomValue = rangeMin + (rangeMax - rangeMin ) * r.nextDouble();

The problem I have is that it keeps giving me a double with 16 decimal places, so i tried using a formatter

Formatter fmt = new Formatter();
fmt.format("%.2f", x);

(its x because I sent randomValue through parameters to another class)

now my big problem is i cant use the number i formatted in anything. For example i cant use it in an if statement, as it gives me an error

    if(fmt > 1000) {
    System.out.print("it worked");
}

i know i cant compare a Formatter to an int in the same way i cant compare strings and longs, but how do i get the random double number i formatted or somehow change it back into a double so that i can use it?




Aucun commentaire:

Enregistrer un commentaire