英文:
How do I round a double to the thirds place?
问题
double1 = 0.05100000000003
double2 = 0.05295
# 如何将小数保留三位小数?分别如下输出:0.051 和 0.053。
# 我尝试了 Math.round(double1); 但是得到了 0.0。
# 有任何想法将不胜感激,谢谢。
英文:
double1 = .05100000000003;
double2 = .05295;
How do I round a decimal to three places? Respectively, I'd like the output to do this 0.051 and 0.053.
I tried Math.round(double1); but I got back 0.0.
Any ideas would be greatly appreciated thanks.
答案1
得分: 1
尝试在Java中使用以下代码。零的数量表示您想要舍入到小数点后多少位(在此例中有3个零)。
(double)Math.round(value * 1000d) / 1000d
编辑:在此前的StackOverflow帖子中提供了相同的答案。
英文:
Try the following code in Java. The number of zeros indicates how many decimal places you would like to round to. (In this case there are 3 zeros).
(double)Math.round(value * 1000d) / 1000d
EDIT: same answer is provided in this previous StackOverflow Post
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论