76 lines
2.2 KiB
C#
76 lines
2.2 KiB
C#
/****************************************************************
|
||
* 作者:liuzl
|
||
* 版权:PCXBC
|
||
* 创建时间:2022/7/18 10:01:44
|
||
* 描述说明:
|
||
*
|
||
* 修改标识:PC-2022
|
||
* 修改描述:
|
||
*
|
||
*****************************************************************/
|
||
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace YBDevice.PrintTool
|
||
{
|
||
public static class Common
|
||
{
|
||
/// <summary>
|
||
/// 转换为整型
|
||
/// </summary>
|
||
/// <param name="data">数据</param>
|
||
public static int ToInt(this object data)
|
||
{
|
||
if (data == null)
|
||
return 0;
|
||
int result;
|
||
var success = int.TryParse(data.ToString(), out result);
|
||
if (success)
|
||
return result;
|
||
try
|
||
{
|
||
return Convert.ToInt32(ToDouble(data, 0));
|
||
}
|
||
catch (Exception)
|
||
{
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 转换为双精度浮点数,并按指定的小数位4舍5入
|
||
/// </summary>
|
||
/// <param name="data">数据</param>
|
||
/// <param name="digits">小数位数</param>
|
||
public static double ToDouble(this object data, int digits)
|
||
{
|
||
var result = ToDouble(data);
|
||
string numToString = result.ToString();
|
||
int index = numToString.IndexOf(".");
|
||
int length = numToString.Length;
|
||
if (index != -1)
|
||
{
|
||
numToString = string.Format("{0}.{1}",
|
||
numToString.Substring(0, index),
|
||
numToString.Substring(index + 1, Math.Min(length - index - 1, digits)));
|
||
}
|
||
return ToDouble(numToString);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 转换为双精度浮点数
|
||
/// </summary>
|
||
/// <param name="data">数据</param>
|
||
public static double ToDouble(this object data)
|
||
{
|
||
if (data == null)
|
||
return 0;
|
||
double result;
|
||
return double.TryParse(data.ToString(), out result) ? result : 0;
|
||
}
|
||
}
|
||
} |