本文介紹了Java 對任意數字進行四舍五入的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
對于一個簡單的問題,我似乎找不到我正在尋找的答案:如何將任何數字四舍五入到最接近的 int
?
I can't seem to find the answer I'm looking for regarding a simple question: how do I round up any number to the nearest int
?
例如,只要數字為 0.2、0.7、0.2222、0.4324、0.99999,我希望結果為 1.
For example, whenever the number is 0.2, 0.7, 0.2222, 0.4324, 0.99999 I would want the outcome to be 1.
目前為止
int b = (int) Math.ceil(a / 100);
不過,它似乎沒有做這項工作.
It doesn't seem to be doing the job, though.
推薦答案
Math.ceil()
是要調用的正確函數.我猜 a
是一個 int
,它會讓 a/100
執行整數運算.改用 Math.ceil(a/100.0)
.
Math.ceil()
is the correct function to call. I'm guessing a
is an int
, which would make a / 100
perform integer arithmetic. Try Math.ceil(a / 100.0)
instead.
int a = 142;
System.out.println(a / 100);
System.out.println(Math.ceil(a / 100));
System.out.println(a / 100.0);
System.out.println(Math.ceil(a / 100.0));
System.out.println((int) Math.ceil(a / 100.0));
輸出:
1
1.0
1.42
2.0
2
參見 http://ideone.com/yhT0l
這篇關于Java 對任意數字進行四舍五入的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!