How to Convert a String Number with a Decimal to Whole and Fractional Parts

What if you’ve received a number with a whole component and a fractional component as a string? What if you need both pieces separately but not together?

I saw this question come up on stackoverflow and thought it could be useful to answer here as well.

There’s a bit of this question that is, quite frankly, ridiculous. And my answer on stackoverflow was not as in depth as I think it should have been.

Here’s the initial answer:

string input = "127.45";
var numberPieces = input.Split(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
int wholePiece = Int32.Parse(duration[0]);
int fractionalPiece = Int32.Parse(duration[1]);

The key here is to use CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator instead of '.'. This ensures that your code works globally. Did you know that every country does not use the period as the decimal indicator? Some countries use the comma. This will use the correct separator for your user.

The rest is simple enough. The split creates a string array with the first element being the whole component and the second element the fractional component. Both of these are run through Int32.Parse() since they should be integers.

The problem here — that I didn’t address in my stackoverflow answer — is that maybe they aren’t. We haven’t verified that the input format is actually able to be converted to a double.

This is the improved solution:

string input = "123.21";
double result;
bool isDouble = Double.TryParse(input, result, CultureInfo.InvariantCulture);
if(!isDouble) throw new InvalidArgumentException("String provided in incorrect format.");
int wholePiece = Decimal.Truncate(result);
int fractionalPiece = (int)(result - (double)wholePiece);

Now I’m doing TryParse to ensure that the format of the supplied string is actually a double, and still maintaining the global nature of the code with the InvariantCulture in the TryParse parameters.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s