Dardar
Dardar

Reputation: 751

String.Format - moving from C++ to C#

we are upgrading our code from C++ to C# and in alot of place we are formating strings. for exmaple we have something like that:

OurString.Format("amount = %0.2Lf", (long double)amount);

How to convert the %0.2Lf into C# format ? i've tried the following code but it's not the same

string formatString = String.Format("amount = {0}", (long double)amount));

thx

Upvotes: 2

Views: 558

Answers (2)

Tieson T.
Tieson T.

Reputation: 21231

Use format strings: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

You probably want either N2 or F2, depending on whether to include the thousands separator. So,

string formatString = String.Format("amount = {0:F2}", amount);

Edit:

As an simple FYI, if you're constructing a string in a series of distinct steps, you might want to use the StringBuilder class, which has an AppendFormat() method that accepts the same formating options as string.Format():

var builder = new StringBuilder();

// ... Your code to build the first part of the string

builder.AppendFormat("amount = {0:F2}", amount);

// ... whatever else you need to add

builder.ToString(); // outputs your final/completed string.

Whether you use StringBuilder or not depends on how critical memory management and/or performance is to the application; strings in C# are immutable, so when you concat them you are actually creating a brand new string. You can read more here: http://msdn.microsoft.com/en-us/library/system.string.aspx#Immutability

Upvotes: 5

xanatos
xanatos

Reputation: 111890

As Tieson wrote, F2... Just remember that in C the default locale is the C locale. So for example 0.00, while in C# the default locale is the current locale of the user (here in Italy 0,00). So it would be better to do:

string formatString = String.Format(CultureInfo.InvariantLocale, 
                                    "amount = {0:F2}", amount);

if you want to always everywhere format your digits in the same manner. Remember that when I told "here in Italy" also means "if I take my Italian Windows 8 in the USA the default locale will be Italian for me."

Ah... and there aren't long doubles in C# (or in .NET, or in newer versions of VC++ for that reason). Only doubles.

I'll add that using a double (or a long double) for money is an antipattern in itself... There is the decimal type for it.

The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations that require large numbers of significant integral and fractional digits and no round-off errors. The Decimal type does not eliminate the need for rounding. Rather, it minimizes errors due to rounding. For example, the following code produces a result of 0.9999999999999999999999999999 instead of 1.

Upvotes: 3

Related Questions