没有四舍五入.NET十进制格式

编程入门 行业动态 更新时间:2024-10-18 18:16:20
本文介绍了没有四舍五入.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 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十进制格式

本文发布于:2023-11-10 02:41:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574114.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:四舍五入   格式   NET   十进制

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!