保留小数位【推荐】
/// <summary>
/// 保留小数
/// </summary>
/// <param name="number">数值</param>
/// <param name="digit">保留小数位长度</param>
/// <param name="round">是否四舍五入</param>
/// <returns></returns>
private decimal SetDecimal(decimal number, int digit = 2, bool round = false)
{
decimal result = 0M;
if (round)
{
result = Math.Round(number, digit);
}
else
{
string length = "1";
for (int i = 0; i < digit; i++)
{
length += "0";
}
int multiple = Convert.ToInt32(length);
result = Math.Truncate(number * multiple) / multiple;
//result = Math.Floor(number * multiple) / multiple;
}
return result;
}
[HttpGet]
public IActionResult GetRetainDecimals(decimal number = 100.12678M, int digit = 2, bool round = false)
{
var result = SetDecimal(number, digit, round);
return Ok(result);
}
四舍五入,取整
Math.Round(Convert.ToDouble(100.99), 0)
四舍五入,保留2位小数
100.99789.ToString("f2");
不四舍五入,保留2位小数
Math.Floor(Convert.ToDouble(100.99789) * 100) / 100.00;
Math.Truncate(1.3278 * 100) / 100;
向上取整,不四舍五入
Math.Ceiling(1.0);
Math.Ceiling(1.1);
Math.Ceiling(1.5);
Math.Ceiling(3.1);
向下取整,不四舍五入
Math.Floor(1.0);
Math.Floor(1.1);
Math.Floor(1.5);
Math.Floor(1.9);
绝对值
Math.Abs(-1)
计算指定数字的平方根
Math.Sqrt(9)
*
*
*
*
*