2

I have a string, "0.000" (or any similar string), that I would like to convert to a long. I am happy to "chop-off" anything after the decimal.

What is the best way to go about this?

I can convert to double and then to long, but I'm just wondering if there is an easier way. All the following statements throw exceptions:

long l3 = Convert.ToInt64(nrToConvert);

long l1;
long.TryParse(nrToConvert, out l1);

long l2 = long.Parse(nrToConvert);
abatishchev
  • 92,232
  • 78
  • 284
  • 421
willem
  • 22,847
  • 19
  • 68
  • 110
  • possible duplicate of [Double.TryParse or Double.Convert - what is faster and more safe?](http://stackoverflow.com/questions/586436/double-tryparse-or-double-convert-what-is-faster-and-more-safe) – abatishchev Jun 08 '10 at 11:44
  • Best? Best by what criteria? Likely to be most successful, the fastest? Also what do you want to happen if it fails? Throw an exception, throw your own exception, consume the exception and return zero? "Best" depends on many - often competing - criteria. – Binary Worrier Jun 08 '10 at 11:46
  • Also see here: http://stackoverflow.com/questions/2922565/which-one-is-faster-in-processing-and-conversion-int-parse-int-tryparse-con, http://stackoverflow.com/questions/199470/whats-the-main-difference-between-int-parse-and-convert-toint32. – Dirk Vollmar Jun 08 '10 at 11:47

5 Answers5

5

In general when parsing a string value I would firstly parse it to the type it's representing. So in this case parse it as a double since it is a double. And yes I wrote parse not convert by intention. There's so many things that can go wrong when parsing a string so always plan for your parsing to fail! it almost certainly will at some point.

double val;
if(double.TryParse(nrToConvert,out val))
{
  //yous should validate that the value is within the expected range as well
  return (long)val;
}
else
{
  //do some error handling;
}
Rune FS
  • 20,632
  • 6
  • 57
  • 92
  • What if the string is '0.000'? It's been a while since I've done serious C# but if memory serves, that would (very correctly) parse as 0 and not meet the if condition, triggering an error response. If you want to handle errors properly (and never expect a 0) you can't use `TryParse`. – Oli Jun 08 '10 at 12:02
  • 1
    @Oli: The string "0.000" would parse just fine as a double, which means that `TryParse` would return `true`. Try it for yourself. – Dan Tao Jun 08 '10 at 12:20
3

As long as the fraction is zero, you can parse those strings by telling it that a decimal point is acceptable:

        long value = long.Parse("0.000", System.Globalization.NumberStyles.AllowDecimalPoint);

It will however not truncate or round numbers for you, non-zero fractions throw an exception (or fail TryParse). You need to explicitly apply the type of truncation you want:

        long value = (long)decimal.Parse("1.500");

Or use Math.Round, Truncate, Ceiling. Note that you technically should not use double.Parse(), a long has too many digits to be accurately represented by a double (19, double only supports 15 significant digits).

Hans Passant
  • 873,011
  • 131
  • 1,552
  • 2,371
2

Have you tried something link this:

(long)Math.Round(double.Parse("1.234"));

Of course, you should use TryParse first, but this should get you started.

etc
  • 562
  • 3
  • 10
1
long myLong = Int64.Parse('0.000');

It can throw a System.FormatException so cater for that. There's also Int64.TryParse() if you just want it to return 0 if it can't parse.

Oli
  • 215,718
  • 61
  • 207
  • 286
1

None of these will work (you'll get a "String is in the wrong format" exception, the TryParse will just fail), you need to either
1) Convert the string to a double first, then cast to a Long

long lng = (long)Convert.ToDouble(nrToConvert); 

or

2) Trim the decimal from the string and convert that (something like)

string nrToConvert =  "0.000";
nrToConvert = nrToConvert.IndexOf('.') > 0 ? nrToConvert.Substring(0, nrToConvert.IndexOf('.') ) : nrToConvert;

long lng = Convert.ToInt64(nrToConvert);

However I'd go with 1, it better refelects what you're doing (taking a double and converting that to a long)

Binary Worrier
  • 47,526
  • 17
  • 131
  • 178