Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting is Specified but argument is not IFormattable

Tags:

c#

string listOfItemPrices = items.ToSemiColonList(item => string.Format("{0:C}", item.Price.ToString()));

I am simply trying to format the price here to 2 decimal places. Ok, so the string.Format doesn't implement IFormattable? Ok not sure how to get around this so that I can format the decimal (price) here.

like image 644
PositiveGuy Avatar asked May 17 '10 14:05

PositiveGuy


People also ask

What is %s in string format?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string.

What is return by format () method?

format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale. getDefault() method.

How do I format a string in C #?

In C#, Format() is a string method. This method is used to replace one or more format items in the specified string with the string representation of a specified object.In other words, this method is used to insert the value of the variable or an object or expression into another string.

How do you write in string format?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.


2 Answers

By passing item.Price.ToString() to String.Format, you are passing a string, not a decimal.
Since strings cannot be used with format strings, you're getting an error.

You need to pass the Decimal value to String.Format by removing .ToString().

like image 195
SLaks Avatar answered Oct 19 '22 17:10

SLaks


There is no point using string.format here, that is used for adding formatted values into strings. e.g.

String.Format("This is my first formatted string {O:C} and this is my second {0:C}",ADecimal,AnotherDecimal)

If you just want the value of a decimal variable as a formatted string then just pass the string formatter to the ToString() method e.g.

ADecimal.ToString("C");
like image 26
Ben Robinson Avatar answered Oct 19 '22 16:10

Ben Robinson