[英]How can I tell if the result of a float division should be a whole number?
我想知道除法后是整數還是浮點數。
if (5.4 / 0.8 ==integer) // except something that would evaluate as true in this case
{
}
做到這一點的方法之一是使用Mathf.Round
找到最接近整數的結果, Mathf.Approximately
到整數比較的結果:
float f1 = 0.5;
float f2 = 0.1;
float result = f1/f2;
if (Mathf.Approximately(result, Mathf.Round(result)) {
Debug.Log("integer result");
}
浮點數計算會帶來精度問題。
例如, 0.3 / 0.1
等於2.9999999999999996,而不是3。
為了進行比較,您需要四舍五入並檢查差異是否可以接受。
var result = 0.3 / 0.1;
if (Math.Abs(Math.Round(result) - result) < 0.0000001)
{
// Do something
}
使用Math
庫的其他示例當然更好,但是另一種方法是在進行除法之前將值轉換為decimal
(以使轉換處理舍入),然后確保在進行除法Math
時沒有余數將結果除以1
:
private static bool DivisionIsInteger(double numerator, double denominator)
{
return (decimal) numerator / (decimal) denominator % 1 == 0;
}
倒計時從@elgonzo一個哎喲注釋開始......現在
嘗試這個:
var div = 5.4 / 0.8;
var divRound = Math.Round(div);
if (div == divRound)
{
Console.WriteLine("Is integer");
}
else
{
Console.WriteLine("Is Float");
}
我認為最快的方法是:
var a = 5.4;
var b = 0.8;
var result = a / b;
var isInteger = result % 1 == 0;
if (isInteger)
{
....
}
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.