[英]Math operations on integer or floating point values
我可以舉一個例子來解釋。
考慮浮點值,例如2.0、3.0等,輸出必須為數字,即2、3等
如果浮點值像2.1、3.5等,則輸出保持不變,即2.1、3.5
是否對浮點值執行任何數學運算?
您可以輕松檢查浮點數是否有小數位。
if (number % (int) number == 0)
System.out.println((int) number); // you know it has no decimal places
else
System.out.println(number); // it has decimal places and you want to print them
通過簡單地比較,Seffy Golan提供的鏈接提出了一個更好的解決方案
if (number == (long) number) { ... }
我以為我會把它納入答案,因為這是我所不知道的好方法。
我認為@LordAnomander的答案很好,但是有點貴,請嘗試使用:
if (number - (int) number == 0)
System.out.println((int) number); // you know it has no decimal places
else
System.out.println(number); // it has decimal places and you want to print them
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.