How do I round a double to one decimal place? [closed]

人盡茶涼 提交于 2019-12-22 18:19:47

问题


I am trying to get a random double returned to me in the format #.# however I am getting a value of something to this effect: 0.9395772067578356

How do you force only a one decimal return on a random double as I cannot put paraments in the .nextDouble.

        myRandomNumGenerator = new Random();
        loadedValue = myRandomNumGenerator.nextDouble();

回答1:


DecimalFormat oneDigit = new DecimalFormat("#,##0.0");//format to 1 decimal place

System.out.println(oneDigit.format(anyVariable)); //generic usage

loadedValue = Double.valueOf(oneDigit.format(loadedValue));//specific usage posted in comments



回答2:


I don't think you can force a one place return. You can just make it print the one place, however.

System.out.printf("%.1f", loadedValue);

That will print the value to one place.



来源:https://stackoverflow.com/questions/15193739/how-do-i-round-a-double-to-one-decimal-place

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!