user1710944
user1710944

Reputation: 1459

How to convert string to ToString("#,##0") format

in my application i am update my ui with my label and i want to show the number in #,##0 format. myClass.getNumberOfFiles return string.

myLabel.Text = myClass.getNumberOfFiles();

Upvotes: 2

Views: 9555

Answers (3)

Rob
Rob

Reputation: 517

int files;
if (int.TryParse(myClass.getNumberOfFiles(), out files)) {
    myLabel.Text = files.ToString("N0");
}

This won't work if you have any formatting in the number already I think. It will work though if on the return of getNumberOfFiles() someone was turning an int into a string. If getNumberOfFiles() is returning a formatted string, you will need to do some different stuff. Below assumes the formatting is in the en-US format coming in and you want to display it in Brazilian Portuguese for example. It is shown in a verbose manner so you know how to plug other cultures in if you need to. If its formatted and doesn't need to change between cultures I don't know why you couldn't just assign the return of getNumberOfFiles() directly to the label's Text property.

int files;
var incomingCulture = CultureInfo.CreateSpecificCulture("en-US");
var outgoingCulture = CultureInfo.CreateSpecificCulture("pt-BR");
if (int.TryParse(myClass.getNumberOfFiles(), NumberStyles.Number, incomingCulture, out files)) {
    myLabel.Text = files.ToString("N0", outgoingCulture);
}

That being said I agree with all the others saying it is ridiculous to return a string for an integer. But I know sometimes you don't have the luxury of being able to change it.

I'll also point out that if you use the named format specifiers like "N0", one day a programmer coming behind you will bless you in their heart when they have to globalize your code. This is because every CultureInfo instance has an implementation for each of the named formats, however it is impossible for it to have implementations for custom format specifiers.

Upvotes: 4

Henk Holterman
Henk Holterman

Reputation: 273474

Assuming getNumberOfFiles returns a string (which, by its name, it shouldn't) :

myLabel.Text = int.Parse(myClass.getNumberOfFiles()).ToString("#,##0");

Upvotes: 7

Jon Skeet
Jon Skeet

Reputation: 1502186

I suspect you want the standard "numeric" format specifier, with a precision of 0:

label.Text = GetNumberOfFiles().ToString("N0");

This is after you've fixed your getNumberOfFiles() method to be GetNumberOfFiles() (naming convention) and made it return int or long (a method which is meant to fetch a number should not return a string).

This will use the appropriate grouping for the current culture; if you want a different culture you can specify it as a second argument.

Upvotes: 5

Related Questions