4 回答

TA貢獻(xiàn)1725條經(jīng)驗 獲得超8個贊
使用這個問題的標(biāo)記答案:
static void Main()
{
Console.WriteLine("DECIMAL");
decimal dTest = 1.527m;
var dTest2 = dTest;
while(dTest2 < dTest*1.1m)
{
dTest2 = RoundUp(dTest2);
Console.WriteLine(dTest2);
}
Console.WriteLine("FLOAT");
float fTest = 1.527f;
var fTest2 = fTest;
while(fTest2 < fTest*1.1f)
{
fTest2 = RoundUp(fTest2);
Console.WriteLine(fTest2);
}
}
static decimal RoundUp(decimal input)
{
int precision = BitConverter.GetBytes(decimal.GetBits(input)[3])[2];
decimal factor = (decimal)Math.Pow(10,precision-1);
return Math.Ceiling(input*factor)/factor;
}
static float RoundUp(float input)
{
return (float)RoundUp((decimal)input);
}
輸出:
DECIMAL
1.53
1.6
2
FLOAT
1.53
1.6
2

TA貢獻(xiàn)1818條經(jīng)驗 獲得超3個贊
為什么不通過簡單的 10 次冪乘法來實現(xiàn),這可以有效地移動小數(shù)點,您可以在其中調(diào)用 Math.Ceiling 將數(shù)字向上取整。除以 10 的相同冪以將小數(shù)點放回原來的位置。
使用decimal.ToString()為“避開”的浮點精度的問題,看到這個博客帖子獲取更多信息
var values = new[] { 1.527f, 1.53f, 1.6f, -1.527f };
for (var i = 0; i < values.Length; i++)
{
var val = (decimal)values[i];
var precision = (decimal.GetBits(val)[3] >> 16 & 0xff) - 1;
var power = (decimal)Math.Pow(10, precision);
if (val < 0)
val = Math.Floor(val * power) / power;
else
val = Math.Ceiling(val * power) / power;
Console.WriteLine(val);
}
輸出
1.53
1.6
2
-1.53
注意 Math.Pow和Math.Ceiling是對 的操作double,因此強制轉(zhuǎn)換為doublefromfloat
更新計算出它需要舍入到多少小數(shù)位并使用小數(shù)來“解決”浮點精度問題。
更新 2用于decimal.GetBytes獲得數(shù)字的精度,而不是執(zhí)行相當(dāng)繁瑣的文化不變ToString().Splityada yada yada。
更新 3對于負(fù)數(shù),從零開始舍入并按位添加& 0xff以去除符號位。

TA貢獻(xiàn)1893條經(jīng)驗 獲得超10個贊
獨立于文化的解決方案:
static double RoundUp(double val)
{
double a = val;
double decimals = a - ((int)a); //Gets only decimals
double pow = Math.Pow(10, decimals.ToString().Length - 3);
a = a * pow; //Multiply by a power of 10 | decimal shift
a = Math.Ceiling(a); //Round up
a = a / pow; //Shift back
return a;
}
并稱之為:
var res = RoundUp(1.527); //1.53
res = RoundUp(1.53); //1.6
res = RoundUp(1.6); //2
或?qū)τ诟↑c數(shù):
static float RoundUp(float val)
{
float a = val;
float t = a - ((int)a); //Gets only decimals
float pow = (float)Math.Pow(10, t.ToString().Length - 3);
a = a * pow; //Multiply by a power of 10 | decimal shift
a = (float)Math.Ceiling(a); //Round up
a = a / pow; //Shift back
return a;
}
var res = RoundUp(1.527f); //1.53
res = RoundUp(1.53f); //1.6
res = RoundUp(1.6f); //2

TA貢獻(xiàn)1777條經(jīng)驗 獲得超10個贊
var a = "1,53";
將此字符串拆分為兩個,并計算小數(shù)位數(shù):
var length = a.Split(',')[1].Length;
將原始字符串轉(zhuǎn)換為雙變量(替換,
為.
以避免轉(zhuǎn)換過程中出現(xiàn)異常):
var b = Convert.ToDouble(a.Replace(',', '.'))
以指定的精度執(zhí)行舍入:
var c = Math.Ceil(b, (length - 1));
并返回值替換.
為,
:
return c.ToString().Replace('.', ',');
- 4 回答
- 0 關(guān)注
- 231 瀏覽
添加回答
舉報