c#中decimal的去0显示

C# 去掉小数点后面多余的0(3种方法实现) 1、使用TrimEnd() decimal num1=(decimal)0.5; //第一步将浮点数转换成字符串 string strNum=num1.ToString(); //第二步使用TrimEnd() if(strNum.Contains(".")){//字符串为浮点数 strNum=strNum.TrimEnd("0").TrimEnd(".");//0.5 } 2、使用Tostring() decimal num1=(decimal)0.5; string strNum=nu 阅读详情

在进来的开发中,遇到到了decimal中显示0的问题,搞了很久才搞好了,现在就简单介绍一下其中一小部分,其他的网上很上很多

public static string DecimalToString(decimal d)
        {
            return d.ToString("#0.######");
        }

这个的显示很简单给几个例子就懂了,注意第一个结果,是会四舍五入的

private void button1_Click(object sender, EventArgs e)
        {
            decimal d0 = 0.0000006m;
            decimal d1 = 0.005000m;
            decimal d2 = 1.00005m;
            decimal d3 = 200.00000m;
            decimal d4 = 200.00006m;
            Console.WriteLine(DecimalToString(d0));
            Console.WriteLine(DecimalToString(d1));
            Console.WriteLine(DecimalToString(d2));
            Console.WriteLine(DecimalToString(d3));
            Console.WriteLine(DecimalToString(d4));
        }

结果如下:

0.000001
0.005
1.00005
200
200.00006

后面的0会给去除,如果小于0的数,0个位还是0,这样就比较符合用户的需求的习惯。

再附加上#和0这两个符号的说明:

以下文字取自:链接

5、零占位符和数字占位符

string.Format("{0:0000.00}", 12394.039) 结果为:12394.04

string.Format("{0:0000.00}", 194.039) 结果为:0194.04

string.Format("{0:###.##}", 12394.039) 结果为:12394.04

string.Format("{0:####.#}", 194.039) 结果为:194

0.0001%误差?C# decimal让利息计算精准到小数点后12位! 摘要: 金融软件中利息计算的精度至关重要,使用C#的decimal类型可有效避免float带来的误差。数据显示,float计算误差达0.01%(百万贷款年误差$100),而decimal精度高达0.0001%(误差仅$1)。通过四舍五入、货币适配等场景优化,decimal能显著降低客户投诉率(从15%降至0.5%)。代码示例展示了简单/复利计算及特殊场景处理,为金融系统提供高精度解决方案。 关键词: C# decimal、利息计算、金融精度、误差优化、复利公式 阅读详情

相关推荐

2025软考信息安全工程师真题

2025信息安全工程师软考真题

qq_40424393的博客 1707

C# 格式化字符串方法 ToString()

C# 格式化字符串方法 ToString() 微软官方说明链接:https://docs.microsoft.com/zh-cn/dotnet/standard/base-types/standard-numeric-format-strings 格式说明符 “属性” 描述 示例 “C”或“c” 货币 结果:货币值。 受以下类型支持:所有数值类型。 精度说明符:十进制小数位数。 默认值精度说明符:由 NumberFormatInfo.CurrencyDecimalDigits 定

elecfriend的博客 1700

[LVGL]:MACOS下使用LVGL模拟器

[LVGL]:MACOS下使用LVGL模拟器

LINKKEEE的博客 2456

终极办法:去掉C# decimal 类型的数据小数点后的无效0

去掉C# decimal 类型的数据小数点后的无效0 一、前言 C# 中decimal类型运算时可能会导致一种情况: 明明运算结果是整数,偏偏输出之后后面跟了一堆无效的零 例如:2000.0000000000000000000000M 或者:684684.16464000000000000000M 那么这个问题该如何解决呢? 二、原因 decimal类型为十进制数据类型,精度非常高,通常用来存储金...

qq_25986069的博客 1万+

AI量化投资开源平台——Qlib(微矿)的学习使用笔记(随缘更新)

Qlib 涵盖了量化投资的全过程,为用户的 AI 算法提供了高性能的底层基础架构,从框架设计上让用户可以更容易地应用 AI 算法来辅助解决量化投资的各个关键问题(例如 Alpha 预测,风险预测,市场动态性建模)。本文旨在记录一些面向初学者的基础内容。

in_void的博客 3133

顶级AI大模型白嫖ChatGPT Plus1个月,0成本薅顶配功能

Chat*** Plus限时免费1个月!原价20美元/月的顶配功能

BUG猿的博客 7283

php读取decimal显示00000,c#中decimal的去0显示

在进来的开发中,遇到到了decimal中显示0的问题,搞了很久才搞好了,现在就简单介绍一下其中一小部分,其他的网上很上很多public static string DecimalToString(decimal d){return d.ToString("#0.######");}这个的显示很简单给几个例子就懂了,注意第一个结果,是会四舍五入的private void button1_Click(...

weixin_31089065的博客 382

【QNX+Android虚拟化方案】136 - QNX 侧 Coredump 文件解析

【QNX+Android虚拟化方案】136 - QNX 侧 Coredump 文件解析

|~~~热爱生活、努力学习的小伙汁~~~| 1909

C# decimal类型

decimal关键字表示 128 位数据类型。 同浮点型相比,decimal类型具有更高的精度和更小的范围,这使它适合于财务和货币计算。 decimal的精度比double高,但数值范围比double小。decimal虽然是128位,但这只是因为它的小数位可以很多,但整体数值范围却没有double大。 类型 精度 范围 占用位 decimal 28~29位有效 ...

health的博客 1万+

【NVIDIA】Jetson Orin Nano系列:烧写Ubuntu22.04

Jeson Orin Nano系列:烧写Ubuntu22.04 电脑主机可以是Ubuntu20.04

郭老二 4895

基于MATLAB的变分模态分解(VMD)算法详解

变分模态分解(VMD)是一种先进的信号处理方法,通过变分框架将复杂信号分解为多个模态分量。相比传统经验模态分解(EMD),VMD具有坚实的数学基础,能有效抑制模态混叠和端点效应。其核心思想是将信号分解转化为约束优化问题,通过交替方向乘子法迭代求解各模态的中心频率和带宽。VMD在机械故障诊断、生物医学信号处理等领域展现出优越性能,尤其适合处理非平稳非线性信号。该算法通过严格的数学模型实现自适应频谱优化,为信号分析提供了更可靠的工具。

qq_42212808的博客 735

C# decimal

一直很奇怪C#的预定义数据类型中为什么加了一个decimal,有float和double不就够了吗?今天来挖一挖。 浮点型   Name CTS Type De script ion Significant Figures Range (approximate) float System.Single

Godsight的博客 3682

Pytorch实用教程:super(MLP,self).__init__()和super().__init__()有什么区别?

在 Python 中,super()函数用于调用父类(超类)的方法。它的使用在继承关系中非常常见,特别是在初始化继承自父类的属性时。在 PyTorch 中,这通常见于初始化nn.Module类的子类。super()的两种调用方式有微妙的差别,但在 Python 3 中常常用来达到同样的目的。这种写法在 Python 2 中非常常见。这里,super()被调用时需要指定当前类名(MLP)和当前实例(self。

若北辰 1026

C#中级、double和decimal有什么区别

double64 位双精度浮点数,基于IEEE 754 标准速度快、范围大,但有舍入误差→ 适合科学计算、图形、物理模拟。decimal128 位高精度十进制数无二进制舍入误差,专为金融和货币计算设计 → 精确但速度慢、范围小。问题答案哪个更精确?decimal(十进制无误差)哪个更快?double(硬件加速)存钱用哪个?必须用decimal0.1 能精确表示吗?double❌,decimal✅字面量怎么写?double3.14;decimal3.14m💡记住double为速度而生,

m0_52276169的博客 1170

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C# 处理 JsonConvert.SerializeObject 序列化对象中decimal类型默认带 .0 的问题

测试写的例子如下:using Newtonsoft.Json; using System; namespace Demo { public class DemoJson : JsonConverter { private void dumpNumArray&lt;T&gt;(JsonWriter writer, T n) { ...

大表哥 2万+

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

C# decimal保留两位小数

C# decimal保留两位小数 *solution 1 个人推荐 最简单 decimal d = 46.28111; string dStr = Math.Round( d,2 ).ToString(); *solution 2 decimal a = 46.28111; string result=a.ToString("#0.00"); *solution 3 decimal d =...

qq_43469252的博客 9678

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

c# decimal 四舍五入

当:decimal sum = 123456.784M; sum = decimal.Round(sum, 2 , MidpointRounding.AwayFromZero); sum的值为:123456.78 当:decimal sum = 123456.785M; sum = decimal.Round(sum, 2 , MidpointRounding.AwayFromZero...

az44yao的专栏 3973

不小心又中了decimal的埋伏——重新捋一下decimal的相关知识

大家都知道在程序语言和数据库中各种数字类型decimal,numeric,float,double,real……,有时候不小心就会出现问题,除了掌握基本的数据存储原理,还要仔细了解各个语言和产品里的细节差别,即便如此,一不小心还是有可能中了埋伏。 在SQLserver中Deci

ETZRP的专栏 1万+

C# 的decimal精度入库的问题

首先说一下C# 和 SQL 中的decimal默认都是 (18,2) 。 就算SQL把精度改成 (18,4),C#进去的数据依旧是(18,2),第三四位小数,根本进不了,比如插入0.1234直接数据库成0.1200 那么可能会出现统计的一些问题-----对不齐。。。然后领导各种喷。。 mvc中,需要对字段重新定义字段类型,就是codefirst的那一套。 摘要: 允许为模型中的实体类...

陈熙之的博客 2762

c# - double 与 decimal

Double与Decimal的区别如下: class Program { static void Main(string[] args) { double a = 0.3 - 0.2; double b = 0.2 - 0.1; Console.WriteLine(a == b); ...

yuxuac的专栏 5361

C#中的decimal类型及用法

C#中的decimal类型及用法 转载:https://blog.youkuaiyun.com/u010771437/article/details/40867831/ decimal(C#) decimal 关键字指示 128 位数据类型。 与浮点型相比,decimal 类型具有更高的精度和更小的范围,这使它适合于财务和货币计算。decimal 类型的大致范围和精度如下所示。 类型 ...

guang670248515的专栏 5万+

[C#] decimal 转换为 string

用 toString: public static string ReadExchangeRate(string fromCurrencyCode, string toCurrencyCode) { BaseCurrency = fromCurrencyCode; decimal conversion = PreformConversion(toCurrencyCode); ...

学习笔记 1万+
上一篇: Linq Distinct方法的扩展
下一篇: nuget学校笔记 搭建属于自己的NuGet服务器
make1828
博客等级 码龄19年 60粉丝 105原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值