I have an object
which may be boxed from int
, float
, decimal
, DateTime
, TimeSpan
etc.
Now I want to convert it to a string
with a format string, such as "D4"
, "P2"
, or "yyyyMMdd"
. But the object
class doesn't have a ToString
method which receives the format string. So the following code doesn't work.
string Format(object value, string format)
{
return value.ToString(format); // error
}
Below is my ugly workaround.
string Format(object value, string format)
{
if (value is int) return ((int)value).ToString(format);
if (value is float) return ((float)value).ToString(format);
if (value is double) return ((double)value).ToString(format);
if (value is decimal) return ((decimal)value).ToString(format);
if (value is DateTime) return ((DateTime)value).ToString(format);
if (value is TimeSpan) return ((TimeSpan)value).ToString(format);
...
}
Is there a smarter way?
Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.
%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string.
Converting Object to String Everything is an object in Python. So all the built-in objects can be converted to strings using the str() and repr() methods.
The most common way how we format strings is by using string. Format() . In C#, the string Format method is used to insert the value of the variable or an object or expression into another string.
There is an interface for that, it is IFormattable
:
public static string Format(object value, string format, IFormatProvider formatProvider = null)
{
if (value == null)
{
return string.Empty;
}
IFormattable formattable = value as IFormattable;
if (formattable != null)
{
return formattable.ToString(format, formatProvider);
}
throw new ArgumentException("value");
}
(this interface is the one used by the various string.Format
, Console.Write
, ...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With