用星号填充值 [英] Pad out value with asterisks

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

问题描述

有没有人有一个代码片段,我可以轻松地显示带有星号的数字值?



我正在使用:

Does anybody have a code snippet where I can easily display a numeric value with leading asterisks?

I am using:

IFormatProvider myFormatProvider = new System.Globalization.CultureInfo("nl-NL").NumberFormat;



给我我想要使用的CultureInfo,以及我可以得到一个值来以正确的格式显示数值,例如:


to give me the CultureInfo I want to use, and I can get a value to display a numeric value in the correct format, for example:

theNumberToConvert.ToString("N4", myFormatProvider);



会给我,例如:



10.000.000,0000



...但是我如何得到这个值来填充这个值:



**。***。** 10.000.000 ,0000?


which will give me, for example:

10.000.000,0000

...but how would I get this value to pad out this value to something like:

**.***.**10.000.000,0000 ?

推荐答案

同样,我没有任何标准,只要我测试过它(假定固定宽度填充):

Again, I've nothing standard, this works as far as I've tested (assumes fixed width padding):
var cultureInfo = new System.Globalization.CultureInfo("nl-NL");
var numberFormatProvider = cultureInfo.NumberFormat;
var chars = theumber.ToString("0000,0000,000,000.#####",  numberFormatProvider).ToCharArray();
for (int i=0; i< chars.Length; i++)
{
    if(chars[i]=='.'  || chars[i]==',' )
        continue;
    if(chars[i] != '0')
        break;
    chars[i] = '*';
}
string paddedText = new string(chars);





虽然可以做一些重构 - 但是对于separtors来说有魔法字符串(来可以是从 cultureInfo.NumberFormat 获得,并且至少不处理负数。我还要抽象出扩展方法。



Could do with some refactoring though - has magic strings for the separtors (come can be got from cultureInfo.NumberFormat) and doesn't handle negatives at the very least. I'd also abstract out to en extension method.


虽然有一个 String.PadLeft [ ^ ]放入星星的方法。

也许,我会做什么使用PadLeft用星星填充未使用的空间,然后使用String.ToCharArray获取字符并手动填写千位分隔符。

然后只使用字符串构造函数将char数组作为将其转换回字符串的参数。
There is nothing standard I know of to do that, although there is a String.PadLeft[^] method which would put in the stars.
Probably, what I would do is use PadLeft to fill the unused space with stars, then use String.ToCharArray to get the characters and fill in the thousands separator manually throughout.
Then just use the string constructor that takes a char array as a parameter to convert it back to a string.


这篇关于用星号填充值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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