MeiRiYiCheng_1_old/YBDevice.PrintTool/Common.cs

76 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/****************************************************************
* 作者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;
}
}
}