- 简要
基于金融行业的开发,经常会涉及单位转换例如:元转万元、元转亿元以及保留小数点精度问题。
讨论Q群:580749909
- 代码
#region 元转万元
/// <summary>
/// 元转为万元
/// </summary>
/// <param name="tenthousand">万元</param>
/// <param name="flotLenght">保留小数位,位数。</param>
/// <returns></returns>
public static decimal ToTenthousand(double money, int flotLenght = 0)
{
decimal tenthousand = (decimal)money / 10000;
return BaseToTenthousand(tenthousand, flotLenght);
}
/// <summary>
/// 元转为万元
/// </summary>
/// <param name="tenthousand">万元</param>
/// <param name="flotLenght">保留小数位,位数。</param>
/// <returns></returns>
public static decimal ToTenthousand(decimal money, int flotLenght = 0)
{
decimal tenthousand = money / 10000;
return BaseToTenthousand(tenthousand, flotLenght);
}
/// <summary>
/// 元转为万元
/// </summary>
/// <param name="tenthousand">万元</param>
/// <param name="flotLenght">保留小数位,位数。</param>
/// <returns></returns>
public static decimal ToTenthousand(int money, int flotLenght = 0)
{
decimal tenthousand = money / 10000;
return BaseToTenthousand(tenthousand, flotLenght);
}
/// <summary>
/// 元转为万元
/// </summary>
/// <param name="tenthousand">万元</param>
/// <param name="flotLenght">保留小数位,位数。</param>
/// <returns></returns>
public static decimal ToTenthousand(long money, int flotLenght = 0)
{
decimal tenthousand = money / 10000;
return BaseToTenthousand(tenthousand, flotLenght);
}
/// <summary>
/// 元转为万元
/// </summary>
/// <param name="tenthousand">万元</param>
/// <param name="flotLenght">保留小数位,位数。</param>
/// <returns></returns>
private static decimal BaseToTenthousand(decimal tenthousand, int flotLenght = 0)
{
decimal result = 0m;
if (flotLenght > 0)
{
result = Math.Round(tenthousand, flotLenght);
}
else
{
result = tenthousand;
}
return result;
}
#endregion
#region 元转亿元
/// <summary>
/// 基类:元转亿元
/// </summary>
/// <param name="money"></param>
/// <param name="flotLenght"></param>
/// <returns></returns>
public static decimal BaseToBillion(decimal money, int flotLenght = 0)
{
decimal tenthousand = ToTenthousand(money, flotLenght);
decimal billion = tenthousand / 10000;
decimal result = 0.0m;
if (flotLenght > 0)
{
result = Math.Round(billion, flotLenght);
}
else
{
result = billion;
}
return result;
}
/// <summary>
/// 元转为亿元
/// </summary>
/// <param name="money"></param>
/// <returns></returns>
public static decimal ToBillion(double money, int flotLenght = 0)
{
decimal result = (decimal)money;
return BaseToBillion(result);
}
/// <summary>
/// 元转为亿元
/// </summary>
/// <param name="money"></param>
/// <param name="flotLenght"></param>
/// <returns></returns>
public static decimal ToBillion(decimal money, int flotLenght = 0)
{
return BaseToBillion(money);
}
public static decimal ToBillion(int money, int flotLenght = 0)
{
decimal result = money;
return BaseToBillion(result);
}
public static decimal ToBillion(long money, int flotLenght = 0)
{
decimal result = money;
return BaseToBillion(result);
}
#endregion