如何格式化每3个字符小数点的字符串.... [英] How to format a string with a decimal point every 3rd character....

查看:82
本文介绍了如何格式化每3个字符小数点的字符串....的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是这个网站的新手和c#(一个VB程序员)所以请原谅我的任何无知。



我的问题是我有一个字符串表示一个号码。



这个数字可以在0到999999999999之间



我需要代表字符串总是在格式000.000.000.000



例如:



12567将是000.000.012.567

1379468将是000.001.379.468

4500078912将是004.500.078.912



等等



我尝试了很多方法,包括使用正则表达式,字符串格式等。似乎没什么用。



任何帮助都将不胜感激。



谢谢。



我的尝试:



私人字符串OriginalString;



OriginalString =132456;



String.Format(############,OriginalString);



.....

解决方案

对于初学者,不要使用字符串来表示数字:当你想做某事时,它是一个PITA以后跟他们一起玩。始终以适当的数据类型保存数据,并使用Parse,TryParse和/或TryParseExact方法尽早转换为该类型(向用户报告问题)并尽可能晚地转换回字符串进行演示。

早期和晚期设计允许您使用有关用户区域设置和文化的信息,这些信息可能在处理时或您存储信息时可用。



那么只需格式化输出数字:

 long x = 4500078912; 
Console.WriteLine({0:00#\\。### \\。### \\。###},x);
string output = String.Format({0:00#\\。### \\。### \\。###},x);


使用正则表达式的解决方案:

  string  formatted = Regex.Replace(originalString, 。{3}  


0。);


I am new to this site and c# (a VB programmer ) so please excuse any of my ignorances.

My question is this I have a string representation of a number.

The number can be between 0 and 999999999999

I need to represent the the string always in the format of 000.000.000.000

For example:

12567 would be 000.000.012.567
1379468 would be 000.001.379.468
4500078912 Would be 004.500.078.912

Etc.

I have tried many methods including using regex, string format, etc. Nothing seems to work.

Any help would be greatly appreciated.

Thank you.

What I have tried:

Private String OriginalString;

OriginalString = "132456";

String.Format(############,OriginalString);

.....

解决方案

For starters, don't use strings to represent numbers: it's a PITA when you want to do something with them later. Always holds data in the appropriate datatype, and convert to that type as early as possible using the Parse, TryParse, and / or TryParseExact methods (reporting problems to the user as you go) and convert back to a string for presentation as late as possible.
The "early in" and "late out" design lets you use information about the users Locale and Culture which may not be available while processing or if you store the info.

Then it's just a matter of formatting the number for output:

long x = 4500078912;
Console.WriteLine("{0:00#\\.###\\.###\\.###}", x);
string output = String.Format("{0:00#\\.###\\.###\\.###}", x);


There is a solution using regular expressions:

string formatted = Regex.Replace(originalString, ".{3}", "


0.");


这篇关于如何格式化每3个字符小数点的字符串....的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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