简体   繁体   中英

ThreadLocalRandom double 2 decimal

I try to print my Array Double with only 2 decimals. But I can not find in google how to do. Please any help?

package com.company;
import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;

public class java_05_16_05_01 {
    public static void main(String[] args){
        ArrayList<Double> salary=new ArrayList<Double>();
        int NumberPersonSurveyed = ThreadLocalRandom.current().nextInt(1, 10+1);
        for(int i=0; i<NumberPersonSurveyed; i++){
            double salaryPerson = ThreadLocalRandom.current().nextDouble(1000, 10000+1);
            salary.add(salaryPerson);
        }
        System.out.println(salary);
    }
}

Actually the OUTPUT is: [9803.056390825992, 2753.180103177606, 2602.5359323328644, 3319.2942269101018]

But I Expect: [9803.056, 2753.18, 2602.53, 3319.29]

Note I want use ThreadLocalRandom instance of Math.random or similar. Thanks so much!

There are 2 ways of doing this, the most common way I have seen is based off of the C style printf .

System.out.printf("%.2f", sal);

printf uses modifiers determined by % operators. This one specifies that it should print floating point number (the f ) with 2 decimal places (the .2 ). You can find a list of operators here .

Personally I prefer the C# styled MessageFormat

System.out.println(MessageFormat.format("{0,number,0.00}", sal));

MessageFormat backends off of DecimalFormat which represents a number in contexts of # and 0 , where a # represents a potential but not required number, while a 0 represents a required number. Which is to say if you pass 10 into the specified format it would print 10.00 .

Edit :

Just realized it was an ArrayList; you're going to have to iterate through each member of the array and print them out individually.

boolean USE_PRINTF = false;
System.out.print("[");
for(int i = 0; i < salary.size(); ++i)
{
    if(USE_PRINTF) { System.out.printf("%.2f", salary.get(i)); }
    else { System.out.print(MessageFormat.format("{0,number,0.00}", salary.get(i))); }
    if(i < salary.size() - 1) { System.out.print(", "); }
}
System.out.println("]");

Since you are simulating salaries, you could simply generate int values, which will be in cents, and then divide by 100 (and convert to double) to get your result. Like so:

double salaryPerson = ThreadLocalRandom.current().nextInt(100 * 1000, 100 * (10000 + 1)) / 100d;

This approach frees you from string formatting issues, and also allows you to process your data with the exact values if you wish to perform extra operations besides printing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM