C#中Decimal类型截取保留N位小数并且不进行四舍五入操作
作者:junjie 时间:2022-01-22 20:55:59
一、问题描述
开发中,需要使Decimal类型数据保留小数点后的两位小数且不需要进行四舍五入操作,即直接截取小数点后面的两位小数即可。例如:1.245M --> 1.24,而不是1.25
使用Decimal.Round()方法可以实现保留Decimal类型数据小数点后的若干位小数,但是该方法会进行四舍五入操作,而不是直接截取。所以,该方法不可取,在网上搜寻一番也没有找到合适的方法,便自己实现了一个截取Decimal类型数据小数点后若干位的方法。
二、详细的实现代码
using System;
namespace CutDecimal
{
public static class DecimalHelper
{
public static decimal CutDecimalWithN(decimal d, int n)
{
string strDecimal = d.ToString();
int index = strDecimal.IndexOf(".");
if (index == -1 || strDecimal.Length < index + n + 1)
{
strDecimal = string.Format("{0:F" + n + "}", d);
}
else
{
int length = index;
if(n != 0)
{
length = index + n + 1;
}
strDecimal = strDecimal.Substring(0, length);
}
return Decimal.Parse(strDecimal);
}
}
}
三、测试代码及结果
static void Main(string[] args)
{
decimal d = 1.23456789M;
for (int i = 0; i <= 10; i++)
{
Console.WriteLine("{0}", DecimalHelper.CutDecimalWithN(d, i));
}
for (int i = 0; i <= 10; i++)
{
Console.WriteLine("{0}", Decimal.Round(d, i));
}
}
测试代码中,不仅给出了本文实现方法的测试代码,还给出了Decimal.Round()方法的测试代码,最终的运行效果如下图所示。
图1 运行结果
大伙儿,能看出区别吧?
标签:C#,Decimal,截取,保留,小数,四舍五入
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Springmvc模式上传和下载与enctype对比
2022-11-08 09:14:17
SpringBoot项目部署到腾讯云的实现步骤
2023-01-01 16:58:55
![](https://img.aspxhome.com/file/2023/7/70557_0s.png)
简单了解Spring中BeanFactory与FactoryBean的区别
2022-01-14 03:59:20
android通过拼音搜索中文的功能实现代码
2022-03-12 04:48:17
![](https://img.aspxhome.com/file/2023/8/93268_0s.png)
Java获取字符串编码格式实现思路
2023-08-14 12:35:38
浅谈Java日志框架slf4j作用及其实现原理
2022-11-02 19:02:04
![](https://img.aspxhome.com/file/2023/8/66228_0s.png)
springboot @ConditionalOnMissingBean注解的作用详解
2021-11-27 09:33:59
![](https://img.aspxhome.com/file/2023/4/61794_0s.png)
如何基于Java实现对象List排序
2022-01-28 03:59:16
Spring Boot中操作使用Redis实现详解
2023-11-24 02:39:29
![](https://img.aspxhome.com/file/2023/9/85399_0s.png)
基于集合的子集与集合的全排列的相关问题
2023-09-23 07:03:46
Proxy实现AOP切面编程案例
2023-07-23 06:44:52
![](https://img.aspxhome.com/file/2023/6/61086_0s.jpg)
C#泛型与非泛型性能比较的实例
2022-01-31 17:26:51
![](https://img.aspxhome.com/file/2023/5/98225_0s.jpg)
SpringBoot整合ES解析搜索返回字段问题
2023-01-26 21:39:53
C#客户端HttpClient请求认证及数据传输
2023-06-11 21:11:00
![](https://img.aspxhome.com/file/2023/8/100148_0s.jpg)
简述Java中的四种引用类型
2023-11-29 00:46:56
C# 中如何利用lambda实现委托事件的挂接
2022-02-06 03:18:00
C# 中用 Sqlparameter 的两种用法
2022-11-19 03:52:52
浅谈Java安全之C3P0的使用
2022-06-06 00:22:11
![](https://img.aspxhome.com/file/2023/9/81349_0s.jpg)
C# SendMail发送邮件功能实现
2022-05-02 19:40:43
C#结合AForge实现摄像头录像
2021-06-28 03:53:51
![](https://img.aspxhome.com/file/2023/5/76425_0s.png)