using System;
using System.Collections.Generic;
using System.Linq;
namespace Opsoft.NetCore.O3App.Shared
{
public static class DecimalExt
{
public static Int32 ToInt32( this decimal value )
{
return decimal.ToInt32( value );
}
/// 转换成百分比格式字符串
/// 任意有效的decimal数值
/// 放大倍数,默认是100
/// 保留小数位数,默认是2
/// 后缀,默认是%
/// 如果值时0默认返回的内容,默认是--
/// 返回格式化后的字符串
public static string SwitchPercentage( this decimal rate, int magnification = 100, int decimals = 2, string suffix = "%", string zeroRepalce = "--" )
{
decimal amplifyRate = rate * magnification;
if ( amplifyRate <= decimal.Zero )
{
return zeroRepalce;
}
return string.Concat( Math.Round( amplifyRate, decimals ), suffix );
}
///
/// 求平均值,如果不能整除,则按照334规则拆分。
/// eg. 10m.Avg(3) --> [ 3m, 3m, 4m ]
///
/// 总金额
/// 拆分份数,如果小于等于0,则当1份拆分。
///
public static List Avg(this decimal totalAmount, int copies)
{
copies = Math.Max(1, copies);
if (copies == 1 || totalAmount % copies == 0m)
{
return Enumerable.Repeat(totalAmount / copies, copies).ToList();
}
int per = (int)(totalAmount / copies);
var splited = new List(Enumerable.Repeat(per * 1m, copies - 1));
splited.Add(totalAmount - splited.Sum());
return splited;
}
}
}