我有這樣一個值:如何將數字四捨五入到一定範圍內?
421.18834
我不得不帶着面具可以是這樣的正確詳談數學:
0.05
0.04
0.1
例如,如果掩碼是0.04,我必須得到值421.20
,因爲.18比.16更接近.20。
,我發現使用谷歌沒有工作的所有功能。
你能幫我嗎?
我有這樣一個值:如何將數字四捨五入到一定範圍內?
421.18834
我不得不帶着面具可以是這樣的正確詳談數學:
0.05
0.04
0.1
例如,如果掩碼是0.04,我必須得到值421.20
,因爲.18比.16更接近.20。
,我發現使用谷歌沒有工作的所有功能。
你能幫我嗎?
double initial = 421.18834;
double range = 0.04;
int factor = Math.round(initial/range); // 10530 - will round to correct value
double result = factor * range; // 421.20
您不需要特殊功能。您將原始數字乘以(1/mask),將其四捨五入爲小數點,然後再以相同因子進行分割。
實施例用0.05
factor = 1/0.05 = 20
421.18834 * 20 = 8423.7668
int( 8423.7668) = 8424
8424.0/20.0 = 421.20
實施例用0.01
factor = 1/0.1 = 10
421.18834 * 10 = 4211.8834
int(4211.8834) = 4212
4212.0/10.0 = 421.20
注意:在Java中,'4212/10'不會生成'421.20'! – fredley
兩個fredley和利瑪使假定四捨五入因子本身是100倍。對於因素如0.06或0.07,這是一個不正確的假設。
這裏是我的Java程序:
public double rounded(double number, double factor) {
long integer = (long) number;
double fraction = number - integer;
double multiple = (fraction/factor);
multiple = Math.round(multiple);
return factor * multiple + integer;
}
相反,你可能會得到大約這裏乘除的答案,你不能這樣做,因爲準確浮點沒有小數。需要轉換爲十進制基數然後四捨五入。 BigDecimal會這樣做。
應此'(INT)(初始/範圍)'輪正確?正如我在幾個月前看到的那樣,這只是削減小數點而不是四捨五入(我猜也是一樣)。如果我使用Math.round,它可以工作。 –
看起來,我的Java有點生疏:-)但''Math.round()'*將*正確地做到這一點! – fredley