没有四舍五入.NET十进制格式 [英] decimal formatting without rounding .net

查看:159
本文介绍了没有四舍五入.NET十进制格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我问这个一般性问题有关小数和内部precisions。以下是有关方案我想解决一个具体的问题。

Yesterday I asked this general question about decimals and their internal precisions. Here is a specific question about the scenario I'm trying to address.

我在SqlServer的列,它的类型 - 十进制(18,6)。 当我取这些值,所创建的.NET小数匹配precision在数据库中。他们是这样的:

I have column in SqlServer that is typed - decimal(18,6). When I fetch these values, the .net decimals that are created match the precision in the database. They look like this:

1.100000
0.960000
0.939000
0.844400
0.912340

我需要present(的ToString)根据这些规则,这些值:

I need to present (ToString) these values according to these rules:

  • 非零总是显示。
  • 在尾随或之前的第n个小数位零显示的。
  • 在第n个位小数结尾零将不显示。

所以,这就是我要当n为3:

So, this is what I want when n is 3:

1.100
0.960
0.939
0.8444
0.91234

现在,我已经写了一些code,它的ToString的十进制 - 删除所有尾随零,然后分析该字符串寻找一个小数点和计算的小数位数,看看有多少尾随零需要被添加重新打开。 有没有更好的方式来做到这一点?

Now, I have written some code that ToString's the decimal - removing all trailing zeroes, and then analyzes the string looking for a decimal point and counts the number of decimal places to see how many trailing zeroes need to be added back on. Is there a better way to accomplish this?

另外,我知道我说的ToString在上面的问题...但如果​​我可以修改他们的方式在小数出我的数据访问层,这样,消费者总是小数与适当的precision,即会更好。是否有可能不字符串操作执行上的小数本身这个操作?

Also, I know I said ToString in the question above... but if I could modify the decimals on their way out of my data-access layer, such that consumers always get decimals with the proper precision, that would be better. Is it possible to perform this operation on the decimal itself without string manipulation?

推荐答案

要输出n您的要求的格式= 3,你可以使用:

To output your required format with n=3, you could use:

number.ToString("0.000###")

通过N作为一个参数,那么你可以建立一个自定义字符串格式为:

With n as a parameter, then you could build a custom string format:

string format = "0." + new string('0', n) + new string('#', 6 - n);
s = number.ToString(format);

这篇关于没有四舍五入.NET十进制格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆