0

I have a string in which the data is getting loaded in this format. "float;#123456.0300000" from which i need to extract only 123456.03 and trim all other starting and ending characters. May be it is very basic that i am missing, please let me know how can i do that. Thanks.

2
  • 1
    "all other starting and ending characters" - you've given a starting string of "float;#" but will it always be that? How much do you really know about the format?
    – Jon Skeet
    Commented Jan 16, 2013 at 13:20
  • yes, the string I am getting looks having "float;#" at starting always so far from my testing. But end users are only allowed to see just the decimal part.
    – svs
    Commented Jan 16, 2013 at 13:24

2 Answers 2

1

If the format is always float;# followed by the bit you want, then it's fairly simple:

// TODO: Validate that it actually starts with "float;#". What do you want
// to do if it doesn't?
string userText = originalText.Substring("float;#".Length);
// We wouldn't want to trim "300" to "3"
if (userText.Contains("."))
{
    userText = userText.TrimEnd('0');
    // Trim "123.000" to "123" instead of "123."
    if (userText.EndsWith("."))
    {
        userText = userText.Substring(0, userText.Length - 1);
    }
}

But you really need to be confident in the format - that there won't be anything else you need to remove, etc.

In particular:

  • What's the maximum number of decimal places you want to support?
  • Might there be thousands separators?
  • Will the decimal separator always be a period?
  • Can the value be negative?
  • Is an explicit leading + valid?
  • Do you need to handle scientific format (1.234e5 etc)?
  • Might there be trailing characters?
  • Might the trailing characters include digits?
  • Do you need to handle non-ASCII digits?

You may well want to use a regular expression if you need anything more complicated than the code above, but you'll really want to know as much as you can about your possible inputs before going much further. (I'd strongly recommend writing unit tests for every form of input you can think of.)

2
  • This worked in removing the starting characters, but how can we remove the additional zeros at the end which are not needed. I will keep all these addtional questions checking while i proceed further in my program. Thanks.
    – svs
    Commented Jan 16, 2013 at 13:44
  • @svs: Ah, sorry - I missed that bit. Editing. There are a couple of edge cases I've highlighted there.
    – Jon Skeet
    Commented Jan 16, 2013 at 13:50
0

Why not just do:

String s = "float;#123456.0300000";
int i = int.Parse(s.Substring(s.IndexOf('#') + 1));

I haven't tested this, but it should be close.

Assuming the format doesn't change, just find the character after the '#' and turn it into an int, so you lose everything after the '.'.

If you need it as a string, then just call the ToString method.

Not the answer you're looking for? Browse other questions tagged or ask your own question.