# Question about Decimals/Doubles in calculations

So I’m making a compound interest calculator for the course and I want all of my values to be decimal due to the financial application.

However, when I try to make the values decimal as seen below:

using System; namespace Review { class Program { static void Main(string[] args) { /* use this space to write your own short program! Here's what you learned: DATA TYPES: int, double ARITHMETIC OPERATORS: +, -, *, / INCREMENT/DECREMENT: ++, -- MODULO: % BUILT-IN METHODS: Abs, Pow, Sqrt, Floor, Ceiling, Min, Max Good luck! */ decimal amountInvested = 17223.32m; int amountOfYears = 4; decimal interestRate = 0.17m; decimal compoundInterest = (amountInvested * Math.Pow((1 + interestRate), amountOfYears)); Console.WriteLine("Your total amount will be " + Math.Round(compoundInterest, 2)); Console.WriteLine("Your interest amount is " + Math.Round((compoundInterest - amountInvested), 2)); } } }

I get the following error:

``````Program.cs(23,62): error CS1503: Argument 1: cannot convert from 'decimal' to 'double' [/home/ccuser/workspace/csharp-working-with-numbers-review-working-with-numbers-csharp/e7-workspace.csproj]

The build failed. Fix the build errors and run again.
``````

However when I make everything a double it runs just fine:

using System; namespace Review { class Program { static void Main(string[] args) { /* use this space to write your own short program! Here's what you learned: DATA TYPES: int, double ARITHMETIC OPERATORS: +, -, *, / INCREMENT/DECREMENT: ++, -- MODULO: % BUILT-IN METHODS: Abs, Pow, Sqrt, Floor, Ceiling, Min, Max Good luck! */ double amountInvested = 17223.32; int amountOfYears = 4; double interestRate = 0.17; double compoundInterest = (amountInvested * Math.Pow((1 + interestRate), amountOfYears)); Console.WriteLine("Your total amount will be " + Math.Round(compoundInterest, 2)); Console.WriteLine("Your interest amount is " + Math.Round((compoundInterest - amountInvested), 2)); } } }

You could try explicitly casting them like the (double) or (decimal) in the example.

(I’m not really a C# guy, so no guarantees lol)

2 Likes

Hi,
Unfortunately, Math.Pow doesn’t work with decimals, only doubles. So, as the other answer suggests you’d need to ‘cast’ interestRate as a double for the sake of the operation and then cast back the result to decimal;

i.e.

``````decimal compoundInterest = (amountInvested * (decimal)Math.Pow((1 + (double)interestRate), amountOfYears));
``````

Casting, as you could probably surmise, is telling the program you want to force the value to be a different type. Depending on what type you’re changing to what you can lose detail, but it can also be very useful.

(Note: in Math.Pow, amountOfYears is also being cast to a double. But, because it’s an int, it can do that without potentially losing information and so it doesn’t throw an error.)

Hope that helps.

1 Like