You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.6 KiB
52 lines
1.6 KiB
3 years ago
|
using System;
|
||
|
|
||
|
namespace Binance.TradeRobot.Common.Extensions
|
||
|
{
|
||
|
public static class MathExtension
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// 四舍五入保留小数
|
||
|
/// </summary>
|
||
|
/// <param name="d"></param>
|
||
|
/// <param name="length">保留的位数</param>
|
||
|
/// <returns></returns>
|
||
|
public static decimal Round(this decimal d, int length)
|
||
|
{
|
||
|
return Math.Round(d, length, MidpointRounding.AwayFromZero);
|
||
|
}
|
||
|
|
||
|
/// <summary>
|
||
|
/// string转换decimal
|
||
|
/// </summary>
|
||
|
/// <param name="s"></param>
|
||
|
/// <param name="length"></param>
|
||
|
/// <returns></returns>
|
||
|
public static decimal ToDecimal(this string s, int? length = null)
|
||
|
{
|
||
|
if (!decimal.TryParse(s, out decimal d))
|
||
|
return 0M;
|
||
|
if (length != null)
|
||
|
return d.Round(length.Value);
|
||
|
return d;
|
||
|
}
|
||
|
|
||
|
/// <summary>
|
||
|
/// 截取小数位数,不进行四舍五入
|
||
|
/// </summary>
|
||
|
/// <param name="d"></param>
|
||
|
/// <param name="length">截取的位数</param>
|
||
|
/// <returns></returns>
|
||
|
public static decimal CutDecimal(this decimal d, int length)
|
||
|
{
|
||
|
var dStr = d.ToString();
|
||
|
var dotIndex = dStr.IndexOf(".");
|
||
|
var cutLength = dotIndex + 1 + length;
|
||
|
if (dotIndex == -1 || dStr.Length <= cutLength)
|
||
|
dStr = string.Format($"{{0:F{length}}}", d);
|
||
|
else
|
||
|
dStr = dStr.Substring(0, cutLength);
|
||
|
return decimal.Parse(dStr);
|
||
|
}
|
||
|
}
|
||
|
}
|