DoIt
DoIt

Reputation: 3428

Display commas in a number converted to string using custom string format

I am trying to change the format of an object which can either be an integer or a decimal to add commas (eg., 1000 to be returned as 1,000) using below custom formatter

string temp => $"{value:n0}"

The above works fine but when the value is decimal, it removes decimal points so I came up with below format which retains decimals when the value is decimal but commas are not returned

string temp => $"{value:.#}"

May I know a better way to do this such that below results are obtained?

1000 to be returned as 1,000
13.00 to be returned as 13
13.1 to be returned as 13.1

I only want to include decimals only when they are non zero

Upvotes: 0

Views: 159

Answers (1)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131237

There is no standard format that will return 0 decimals for integral/types values. You can use the #,###.# format to return a string that uses groupind and decimal separators with optional decimal digits. You'll have to specify the number of decimals explicitly.

The line :

Console.WriteLine($"{d:#,###.#}");

Returns strings in the form you specified:

1000       -> 1,000
13         -> 13
13.1       -> 13.1
1234567.8  -> 1,234,567.8

Upvotes: 2

Related Questions