1

Here is a simple calculator, to calculate how much candy you can get when dividing the kilogram price with the money you have allocated for candy.

In example: "Candy costs 5$ a kilo. I have 3.50$ allocated for candy. I would use this program to calculate the amount of candy I get."

It works fine until using decimals. I want to convert the string to Double so I can use decimals with the calculator. 4$ kilo price and 8$ money of course results to 2 kilos of candy. But if the kilo price was 4.80$ and I had 9.30$ money, I would only get an error and cause the command prompt to crash.

static void Main(string[] args)
    {
      //The variables
        int int1;
        int int2;
        string text1;
        string text2;
      //The actual calculation
        System.Console.Write("Please input the kilogram price of candy: ");
        text1 = System.Console.ReadLine();
        int1 = int.Parse(text1);
        System.Console.Write("Please input the money allocated for candy ");
        text2 = System.Console.ReadLine();
        int2 = int.Parse(text2);
        System.Console.WriteLine("With the amount of money you input you would get " + (int2 / int1) + " kilos of candy.");
    }
}

}

6
  • Simply use Double.Parse?! (Although i would recommend using .TryParse) Commented Nov 18, 2015 at 12:45
  • 1
    Use Double.TryParse(text1, out myDoubleVariable); instead of using integers. Integers are, by definition, whole numbers. Commented Nov 18, 2015 at 12:45
  • 2
    why int not double? ps. int1 is a terrible variable name :p Commented Nov 18, 2015 at 12:45
  • 2
    Is your question "Why can't I store 4.80 in an int"? Maybe you need to educate yourself about the various numeric variable types C# offers. Commented Nov 18, 2015 at 12:45
  • 3
    Also, you didn't even provide your error message. Please read FAQ and How to Ask couple of times.. Commented Nov 18, 2015 at 12:49

4 Answers 4

5

You're using int variable types, which can only contain integer numbers, i.e. "whole" numbers without decimals, such as 1 and 42. As soon as you want to use decimals, you'll need a variable type that can support this.

C# has a few of those built in: float, double and decimal. Given you're working with monetary data, where precision and accuracy are very important, you must use decimal.

You also want to use the bool-returning TryParse() as opposed to the exception-throwing Parse() method.

So change your code to use decimal and decimal.TryParse():

decimal pricePerKilogram;
string input = Console.ReadLine();

if (!decimal.TryParse(input, out pricePerKilogram))
{
    // show error or retry
}
Sign up to request clarification or add additional context in comments.

2 Comments

Small addition, it would be better to use an IFormatProvider (like InvariantCulture) in TryParse to specify this . as a NumberDecimalSeparator.
This answer was the most comprehensive and helped me. I am obviously a beginner on C# and somehow I can't assimilate the variable types yet. I'm sure I will in the future as I get going with this language. Thanks! @CodeCaster
3

You need to parse your inputs from decimal, not int. Here, try it this way:

System.Console.Write("Please input the kilogram price of candy: ");
decimal pricePerKilo = decimal.Parse(System.Console.ReadLine());
System.Console.Write("Please input the money allocated for candy ");
decimal amountAllocatedForCandy = decimal.Parse(System.Console.ReadLine());
System.Console.WriteLine("With the amount of money you input you would get " + (amountAllocatedForCandy / pricePerKilo) + " kilos of candy.");
System.Console.Read();

An int is a type that can only store whole numbers -- i.e. no fractional component/decimal digits -- which is why you got an error when you tried to parse a string number with decimal digits into an int. A decimal, on the other hand, is used to store numbers with fractional components.

Each type has its uses: you would never want to store, say, number of candy pieces using a decimal since that can only be a whole number. Doing so could lead to unnecessary confusion for future maintainers of your code and could lead to bugs that are hard to find.

1 Comment

In normal circumstances I think using var almost everywhere is fine, but when OP clearly doesn't know the difference between even the most basic data types, you probably shouldn't use it.
1

that is because 4.80 or 9.30 is not integer.

   double double1;
    double double2;
    string text1;
    string text2;
  //The actual calculation
    System.Console.Write("Please input the kilogram price of candy: ");
    text1 = System.Console.ReadLine();
    double1 = double.Parse(text1);
    System.Console.Write("Please input the money allocated for candy ");
    text2 = System.Console.ReadLine();
    double2 = double.Parse(text2);
    System.Console.WriteLine("With the amount of money you input you would get " + (double2 / double1) + " kilos of candy.");

NOTE: INT stores integer value like 1 2 3 4 etc...

2 Comments

Don't use double for monetary data.
You answer is very bad advice! Never use double for something that needs to be precise!
1

As to your question:

Just use doubles decimals in the first place!

decimal price;
decimal allowance;

Also, some additional unsolicited advice:

You've got a few issues here.

First of all, you'll need to swap your division in the WriteLine statement to get the correct calculation.

Also, I'd recommend renaming your variables to something more descriptive.

Here's your code with some modifications. I've commented each change.

//The variables
    decimal price; //CHANGE: descriptive variables!
    decimal allowance;
    string priceInput;
    string allowanceInput;
//The actual calculation
    System.Console.Write("Please input the kilogram price of candy: ");
    priceInput = System.Console.ReadLine();
    price = decimal.Parse(priceInput); //CHANGE: use double.Parse here instead of int.Parse
    System.Console.Write("Please input the money allocated for candy ");
    allowanceInput = System.Console.ReadLine();
    allowance = decimal.Parse(allowanceInput); //CHANGE: use double.Parse here instead of int.Parse
    System.Console.WriteLine("With the amount of money you input you would get "
        + Math.Round(allowance / price, 2) + " kilos of candy.");
    //CHANGE: Divide the money you have by the amount it costs to get the KG of candy.

EDIT: Added decimals due to working with money.

1 Comment

Your edit is not helpful. It doesn't explain why. Best to just leave it out and remove all references to double, using decimal instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.