简体   繁体   English

千位分隔符的字符串格式

[英]String Format for Thousand separators

Is there a way using String Formatter I can achieve the following: 有没有一种方法可以使用String Formatter实现以下目的:

$52,152 to $52.1 52152至52.1美元

I have a series of values that are all thousands and I will like to display them in the above format. 我有一系列的值,它们都是数千个,我想以上述格式显示它们。

Thanks 谢谢

This works for $52.2 , using the , number scaling specifier : 这适用于$52.2 ,使用,数字比例换算说明符

string.Format("{0:$0,.0}", 52152);

If you really want 52.1 , you'll probably have to do it “manually”; 如果您确实想要52.1 ,则可能需要“手动”执行; sorry. 抱歉。 All custom formatting strings seem to round. 所有自定义格式字符串似乎都是四舍五入。

In your case the non-formatted versions of your 2 numbers are inherently different 您的情况是2个数字的非格式化版本本质上是不同的

52152 != 52.1

A better solution might be to send the correct numbers to the UI but if not, you can use the , scaling specifier - http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SpecifierTh 一个更好的解决方案可能是正确的号码发送到用户界面,但如果没有,你可以使用,缩放符- http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SpecifierTh

void Main()
{
    decimal x = 52152M;

    var a = string.Format("{0:C}", x); //Current Format in Local Culture
    Console.WriteLine(a); //Prints €52,152.00

    var b = string.Format("${0:00000}", x); //Custom Format, no decimals
    Console.WriteLine(b);//Prints $52152

    var c = string.Format("${0:###,###,###}", x); //Custom Format, no decimals + 1000 seperators
    Console.WriteLine(c);//Prints $52,152

    var d = string.Format("${0:###,###,.0}", x); //Custom Format, 1 decimal place, 1000 seperators to support values over 1 million
    Console.WriteLine(d);//Prints $52.2

}

Something like this? 像这样吗

string input = "$52,152";
var number = long.Parse(input, NumberStyles.Currency);
string result = (number / 100L / 10m).ToString("C1");

Explanation. 说明。 First division is an integer division that truncates. 第一除法是截断的整数除法。 Second division is a System.Decimal division. 第二除法是System.Decimal除法。

This assumes a culture (for example new CultureInfo("en-US") ) where the currency sign is "$" and the thousands separator is "," . 这假定一种文化(例如new CultureInfo("en-US") ),其中货币符号为"$" ,千位分隔符为","

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM