Mike
Mike

Reputation: 856

Convert string decimal to int

I have a string "246246.246" that I'd like to pass to the IConvertable interface, ToInt16, ToInt32, ToIn64. What is the best way to parse a string with decimal places to an integer?

This is a solution, but is there a better solution?

string value = "34690.42724";
Convert.ToInt64(Convert.ToDouble(value));

Upvotes: 43

Views: 109060

Answers (5)

king zecole
king zecole

Reputation: 59

The code below is to convert decimal Amount to Kobo value, which is needed when integrating to a payment gateway needing the amount in kobo's or cent.

public static void Main(string[] args)
{          
  decimal amount = 50.567890m; 
        
  int koboValue = 0;
        
  String[] values =  amount.ToString("0.##").Split('.');
        
  int wholeNumber = Convert.ToInt32(values[0]);
        
  if(values.Count() > 1){
        koboValue = Convert.ToInt32(string.Join(string.Empty,values));
  }else{
        koboValue = wholeNumber * 100;
  }
        
  Console.WriteLine(koboValue);
}

Upvotes: 0

Joel Etherton
Joel Etherton

Reputation: 37543

To do this discounting rounding you could do:

Convert.ToInt64(Math.Floor(Convert.ToDouble(value)));

If you need to round you could replace Math.Floor with Math.Round.

Edit: Since you mentioned in a comment that you'll be rounding:

Convert.ToInt64(Math.Round(Convert.ToDouble(value)));

If you have to worry about localization/globalization then as @xls said you should apply a CultureInfo in the conversions.

Edit 2: Alternative method using a string function (not terribly elegant IMO - maybe it could be elegantized with a predicate function):

Convert.ToInt64(value.Substring(0, value.IndexOf('.') > 0 ? value.IndexOf('.') : value.Length));

Upvotes: 79

dbarth
dbarth

Reputation: 238

Assuming this string comes from user input, you probably want to catch number styling. Run it through a reusable function like so...

int? ConvertToNumber(string value)
{
   if (value == string.Empty) return null;

   try
   {
       var dec = decimal.Parse(value,
           NumberStyles.AllowDecimalPoint |
           NumberStyles.Number |
           NumberStyles.AllowThousands);

       return (int)Math.Round(dec);
   }
   catch (Exception ex)
   {
       Console.WriteLine("Please input a number.");
       return null;
   }
}

Upvotes: 0

Sergey Shandar
Sergey Shandar

Reputation: 2387

If you are really worry about accuracy but not about speed then decimal type would be better.

(long)Math.Round(decimal.Parse(value));

Upvotes: 2

deepee1
deepee1

Reputation: 13216

You should not have to Round the value as ToInt64(double) returns the rounded version already

        string value = "246246.246";
        Convert.ToInt64(Convert.ToDouble(value));

Upvotes: 17

Related Questions