0

Is there a way using String Formatter I can achieve the following:

$52,152 to $52.1

I have a series of values that are all thousands and I will like to display them in the above format.

Thanks

Kurubaran
  • 8,696
  • 5
  • 43
  • 65
franciscovalera
  • 111
  • 1
  • 1
  • 14

3 Answers3

3

This works for $52.2, using the , number scaling specifier:

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

If you really want 52.1, you’ll probably have to do it “manually”; sorry. All custom formatting strings seem to round.

Ry-
  • 218,210
  • 55
  • 464
  • 476
1

In your case the non-formatted versions of your 2 numbers are inherently different

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

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

}
Eoin Campbell
  • 43,500
  • 17
  • 101
  • 157
1

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.

This assumes a culture (for example new CultureInfo("en-US")) where the currency sign is "$" and the thousands separator is ",".

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181