techno
techno

Reputation: 6508

Formatting Float Value to specific Format - Java vs C# Number Formatting

I need to convert Byte to KB.So i divide the value by 1024 I need to display the value in this format specified originally in Java Number formatting ###,###,###,##0.00 KB

This code

 string format="###,###,###,##0.00 KB";
 return String.Format(format, x);

produces the following output ###,###,###,##0.00 KB

This formatting string is specified in the Java counterpart,wont the same approach work in C#? Please advice.

Upvotes: 3

Views: 98

Answers (1)

György Kőszeg
György Kőszeg

Reputation: 18023

String.Format and IFormattable.ToString (the formatting you need here) are different, yet related things.

String.Format requires some format string with placeholders and the substituted values can also have formatting if they implement the IFormattable interface.

Console.WriteLine(String.Format("{0} KB", 42.ToString("###,###,###,##0.00")));

The formatting of 42 can be inlined:

Console.WriteLine(String.Format("{0:###,###,###,##0.00} KB", 42));

Which can be simplified further by interpoation:

Console.WriteLine($"{42:###,###,###,##0.00} KB"));

Of course, 42 can be a variable in the interpolation ($"{numValue:###,###,###,##0.00} KB}"). However, the format string cannot be a variable, so this will not work:

string format = "{x} KB";
Console.WriteLine($format); // does not compile, use String.Format in this case

Remark:

Console.WriteLine also supports formatting so the examples above could have been written like this:

Console.WriteLine("{0:###,###,###,##0.00} KB", 42);

I used explicit String.Format just to avoid confusion.


Update

If the size formatting comes from an external source you cannot inline it into the format string but this is not a problem. So if you have

string fileSizeFormat = "###,###,###,##0.00 KB";

You can still use myFloatWithFileSize.ToString(fileSizeFormat). In this case String.Format is needed only if you want to embed this into a nice sentence or something:

return String.Format("The size of the file: {0}", fileSize.ToString(fileSizeFormat));

or with interpolation:

return $"The size of the file: {fileSize.ToString(fileSizeFormat)}";

Upvotes: 2

Related Questions