[英]Get Last 2 Decimal Places with No Rounding
在 C# 中,我試圖在沒有四舍五入的情況下獲得雙精度的最后兩位小數。 我已經嘗試了從Math.Floor
到Math.Truncate
所有Math.Floor
, Math.Truncate
沒有任何效果。
我想要的結果樣本:
1,424.2488298 -> 1,424.24
53.5821 -> 53.58
10,209.2991 -> 10,209.29
有任何想法嗎?
好吧,數學上很簡單:
var f = 1.1234;
f = Math.Truncate(f * 100) / 100; // f == 1.12
將小數點后兩位移到右側,轉換為int以截斷,將其移回左側兩個位置。 框架中可能還有一些方法可以做到這一點,但我現在看不出來。 你可以概括一下:
double Truncate(double value, int places)
{
// not sure if you care to handle negative numbers...
var f = Math.Pow( 10, places );
return Math.Truncate( value * f ) / f;
}
我的建議:首先停止使用double
。 如果你需要十進制舍入,那么賠率是好的,你應該使用decimal
。 你的申請是什么?
如果你有雙,你可以這樣做:
double r = whatever;
decimal d = (decimal)r;
decimal truncated = decimal.Truncate(d * 100m) / 100m;
請注意,如果double的絕對值大於792281625142643375935439504,則此技術將失敗,因為乘以100將失敗。 如果您需要處理大的值,那么您將需要使用特殊技術。 (當然,到雙倍大的時候,你的能力遠遠超出它在小數位后用兩位數表示值的能力。)
double d = Math.Truncate(d * 100) / 100;
Math.Round(NumberToRound - (double)0.005,2)
即
Math.Round(53.5821 - (double)0.005,2) // 53.58
Math.Round(53.5899 - (double)0.005,2) // 53.58
Math.Round(53.5800 - (double)0.005,2) // 53.58
一般解決方案:
public static double SignificantTruncate(double num, int significantDigits)
{
double y = Math.Pow(10, significantDigits);
return Math.Truncate(num * y) / y;
}
然后
double x = 5.3456;
x = SignificantTruncate(x,2);
將產生所需的結果x=5.34
。
Octane 我概括了你的答案,它不會受到超過最大值的影響..就像一個魅力:)
int dec = 4;
return Math.Round(val - (decimal)(5 / Math.Pow(10,dec+1)), dec)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.