Question

I am creating a C# method that should
1. take in a string
2. format that string as Currency (no decimal or cents) and return it

String.Format is great at formatting, but its formatting applies only when printing or outputting the value. When I step through the code, I can clearly see that the value that is actually saved into the string is not formatted. But I need it to be formatted. And that's where your help is needed.

In step 1 above, the string that is input will fall into 1 of 3 possible formats. (Below, I am using " to designate the beginning and end of strings. The " is not actually part of the string.)
1. "<5000"
2. "5000-10000"
3. ">10000"

For these 3 examples, the method should output
1. "<$5,000"
2. "$5,000 - $10,000"
3. ">$10,000"

Basically, the method should add $ and , where needed (what String.Format does so well). The rest of the formatting, like adding in <, >, or - is easy. I can make a method to manually do this, but there's got to be an easier way!

Was it helpful?

Solution 3

(copied from my comment)

If you already have a string variable, let's call it s, saying:

string.Format( /* something with s in it */ )

will not change s itself. You might want to reassign, as in

s = string.Format( /* something with s in it */ )

where on the right-hand side the "old" s object is used, and the result of Format is then "saved" to s and becomes the new s.

But note that String.Format cannot format a string as currency. It can format a number (like a decimal or a double) as a currency, but once you have string, no format like {0:C} or {0:C0} will help change the string output.

OTHER TIPS

Just to make sure, you are assigning the result of String.Format somewhere, right?

string result = String.Format("<{0}>", 123);

Strings in .NET are immutable, so functions always create new strings instead of modifying existing ones. Also, "printing and outputting" is in no way magical, so it's not possible for a function to behave differently when its result is outputted afterwards.

string.Format doesn't modify the string, but returns an entirely new instance. You can assign it to a variable through:

var newString = string.Format("{0} is my format", oldString);

You can solve your problem with a Regex, in case you only have raw strings and not the values inside of them. This applies only to the three examples you brought, but you can adapt it by changing the pattern.

EDIT: I've noticed it doesn't apply the commas, but you can try to modify the pattern to match your desired output. Now it works as the author requested.

string[] samples =
{
    "<5000",
    "5000-10000",
    ">10000"
};
var results = samples.
    Select(s => Regex.Replace(s, @"\d+",
        m => Convert.ToInt32(m.Value).ToString("$#,#"))).
    ToArray();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top