固定的小数位数,没有小数 [英] A fixed number of decimal places with no decimal

查看:56
本文介绍了固定的小数位数,没有小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图屏蔽一个十进制值.

I'm trying to mask a decimal value.

我想让19.76变成1976000,甚至1976

另一个例子是 500.53 会变成 50053000.

Another example would be 500.53 would become 50053000.

我想用 ToString 重载而不是某种转换方法来做到这一点,因为它更适合我的 xml 设置文件.

I would like to do this with the ToString overloads rather than some kind of conversion method as it suits my xml settings file better.

我无法找到一个不假定小数点的 IFormatProvider,但我怀疑这正是我需要的.

I wasnt able to find an IFormatProvider that would not assume a decimal point, I suspect thats what I need however.

如果我像这样在字符串格式中省略小数点:

If I leave out the decimal in the string format like this:

?myvalue
19.76
?((decimal)myvalue).ToString("####000")
"020"

我的值是四舍五入的

推荐答案

答案是,如果不将字符串转换为另一种格式并删除小数点分隔符,就无法做到这一点.

The answer is that you can't do it without converting the string to another format and removing the decimal separator.

没有去除小数点分隔符的基本格式.那么你可以试试内置的 System.Globalization.NumberFormatInfo 但它不接受空分隔符...

There is no basic format that removes the decimal separator. Then you might try the built-in System.Globalization.NumberFormatInfo but it doesn't accept empty separators...

decimal d = 19.76m; 
var format = new System.Globalization.NumberFormatInfo() { NumberDecimalSeparator = string.Empty };
// ArgumentException: Decimal separator cannot be the empty string.
d.ToString(format); 

现在剩下的就是自己实现 IFormatProvider ......这将涉及手动处理数字以删除小数点分隔符(转换为字符串并替换,乘以生成整数等)无论如何!

Now all that's left is to implement IFormatProvider yourself... which will involve manually fiddling with the number to remove the decimal separator (convert to string and replace, multiply to make integer, etc.) anyway!

这篇关于固定的小数位数,没有小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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