There are many web application functionalities, where we need to pass random decimal test data into input field while designing effective automation script.
In this post will illustrate how to generate random decimal data with specific format.
In this post will illustrate how to generate random decimal data with specific format.
Generating random decimal data:
//random float data
float output = min + new Random().nextFloat() * (max - min);
DecimalFormat decimalf = new DecimalFormat(format);
//random double data
double out = min + new Random().nextDouble() * (max - min);
DecimalFormat decimal = new DecimalFormat(format);
Please find the below sample program for the same.
Sample Code:
import java.text.DecimalFormat;
import java.util.Random;
public class RandomDecimalValues{
//specific formats:
//for two decimal values - #.##
//for three decimal values - #.###
//for four decimal values - #.####
//for five decimal values - #.#####
//Generating random decimal values with specific format
public String generateDecimalData(String format,double min,double max) {
//random double
double out = min + new Random().nextDouble() * (max - min);
DecimalFormat decimal = new DecimalFormat(format);
return decimal.format(out);
}
//Usage
public static void main(String[] args){
RandomDecimalValues s = new RandomDecimalValues();
System.out.println(s.generateDecimalData("#.##",2.0d,9.0d));
}
}