java 如何将双精度舍入到小数点后一位?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15193739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I round a double to one decimal place?
提问by Bob
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
我试图以 #.# 格式返回给我的随机双精度值,但是我得到了一个值:0.9395772067578356
How do you force only a one decimal return on a random double as I cannot put paraments in the .nextDouble.
由于我无法在 .nextDouble 中放置参数,您如何强制只返回一位小数返回随机双精度值。
myRandomNumGenerator = new Random();
loadedValue = myRandomNumGenerator.nextDouble();
回答by Benjiman
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
回答by Human Flotsam
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.
这会将值打印到一个地方。