I’m currently reading a long number from a string. The number is 3 integer digits followed by 7 decimal digits without a decimal (e.g. 1234567890).
How can I divide this number before parsing it?
I’m trying to parse it into an integer, but an integer has a ~2 billion maximum value.
Here is what I have tried:
class Program
{
static void Main(string[] args)
{
using (StreamReader reader = new StreamReader("CLIFF.dat"))
{
string line;
var locations = new Dictionary<string, int[]>() {
{"210", new [] {405, 4, 128, 12, 141, 12, 247, 15}},
{"310", new [] {321, 4, 112, 12, 125, 12, 230, 15}}, //
{"410", new [] {477, 4, 112, 12, 125, 12, 360, 15 }}
};
while ((line = reader.ReadLine()) != null)
{
var lineStart = line.Substring(0, 3);
if (lineStart == "210" || lineStart == "310" || lineStart == "410")
{
var currentLocations = locations[lineStart];
var letters = line.Substring(currentLocations[0], currentLocations[1]);
var transactionvolume =
int.Parse(line.Substring(currentLocations[2], currentLocations[3])) +
int.Parse(line.Substring(currentLocations[4], currentLocations[5]));
var watching = line.Substring(currentLocations[6], currentLocations[7]);
var number = int.Parse(line.Substring(currentLocations[6], currentLocations[7])*));
It’s the current location[6] number that is too large and needs to be multiplied by 10^-7.
Shameful rollup of the comments into an answer:
The problem is that a 32-bit signed integer can handle, at most, a value of 2.1 billion (2,147,483,647 to be precise). The value as translated directly from the string is too big.
The possible strategies, as outlined in the comments, are:
Use a larger datatype. Long, double, decimal, bigint etc are all capable of handling numbers in the tens of billions and higher (though with floating-point types, the higher it goes the less precision it has). Since you want a floating-point type and you’re expecting 7 decimal places, personally I’d go with Decimal; it’s the largest datatype at 128 bits, but it has the best precision of a floating type, meaning you can expect to put any integer value in it, divide by 107 and get the right answer.
Divide and conquer. You already have the number as a string, and you know it has exactly 7 decimal points. You therefore know where to put a decimal point into the string such that it can be parsed into a floating-point type: