Double not changing its value properly - c#

I am trying to calculate the Net Income based on a given Gross Income Value. The rules are this :
If grossValue is lower or equal to 1000, no tax is applied
10% Tax is applied to the exess amout
Example : Given a gross value of 3400, we apply 10% tax to the exess so 10% out of 2400 is 240 => Then we just return 2160 + 1000
The problem is this line : double netSalary = exessAmout - (10 / 100 * exessAmout); For some reason the value doesnt change
public double CalculateNetSalary(double grossSalary)
{
// Taxes dont apply, return grossValue
if(grossSalary <= 1000)
{
return grossSalary;
}
double exessAmout = grossSalary - 1000;
// Apply normal tax
double netSalary = exessAmout - (10 / 100 * exessAmout);
return netSalary + 1000;
}
I expected given a value of 3400 to receive 3160
Why :
exessAmout = 3400 - 1000 => 2400
netSalary = 2400 - (10% of 2400)
return netSalary + 1000
using a calculator to solve this I get the right answer, but running the code the value always stays the same

You are doing integer division. When you divide an int by another int then the result will be an int, which means that 10 / 100 will be zero. Make them double literals, i.e. 10.0 / 100.0, and it should work.

First As mentioned jmcilhinney in his answer you need to make this 10 / 100 for double literals. and you expecting here 3160 as an answer? that expected result is breaking in here.
// Apply Social Tax
if (grossSalary > 3000)
{
netSalary -= (10.0 / 100.0 * netSalary);
Console.WriteLine(netSalary);
}
You have applied Social Tax for the netSalary value. 3160. According to it, output should be 2944

Related

Divide by 0 error C# [duplicate]

This simple calculation is returning zero, I can't figure it out:
decimal share = (18 / 58) * 100;
You are working with integers here. Try using decimals for all the numbers in your calculation.
decimal share = (18m / 58m) * 100m;
18 / 58 is an integer division, which results in 0.
If you want decimal division, you need to use decimal literals:
decimal share = (18m / 58m) * 100m;
Since some people are linking to this from pretty much any thread where the calculation result is a 0, I am adding this as a solution as not all the other answers apply to case scenarios.
The concept of needing to do calculations on various types in order to obtain that type as a result applies, however above only shows 'decimal' and uses it's short form such as 18m as one of the variables to be calculated.
// declare and define initial variables.
int x = 0;
int y = 100;
// set the value of 'x'
x = 44;
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0. The conversion to double happens
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );
// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
Because the numbers are integers and you perform integer division.
18 / 58 is 0 in integer division.
Whenever I encounter such situations, I just upcast the numerator.
double x = 12.0 / 23409;
decimal y = 12m / 24309;
Console.WriteLine($"x = {x} y = {y}");
double res= (firstIntVar * 100f / secondIntVar) / 100f;
when dividing numbers I use double or decimal , else I am getting 0 , with this code even if firstIntVar && secondIntVar are int it will return the expected answer
decimal share = (18 * 100)/58;
Solved: working perfectly with me
int a = 375;
int b = 699;
decimal ab = (decimal)a / b * 100;

C# I set a discount but cant get the price - discount but still original price

// here I set the discount which after the subtraction should be 150 euro
public int SetDiscountPrice()
{
return price = price - (10/100)*price;
}
and here I call the method SetDicountPrice but it does not work
Console.WriteLine("\nAfter selling 1 item for {0} euro, number of sofas left is {1}",sofa.SetDiscountPrice(), sofa.SellOneProduct());
int / int = int so your calculation would be x - 0 = x because 10/100 equals 0
If you want to calcualte with floating point values use
return price = (int)(price - (10m / 100m) * price); // m for decimal type
or if you just want to get the value without changing the initial price
return (int)(price - (10m / 100m) * price);
and think about using type decimal for money values
(10/100) is an expression equal to 0 due to integer division.
Given that you've told us that price is an integral type, you ought to use
return price = price - price / 10;
and be aware that this will always round up the result. Alternatively, use
return price = price * 9 / 10;
which will round downwards, but be mindful that this is vulnerable to integer overflow due to an order of magnitude increase in the int during the calculation.
Solution:
An easy fix would either be casting it to a decimal (Note that price has to be a decimal in that case):
return price = price - (decimal)10/100*price;
or use a decimal as the divisor:
return price = price - 10M/100M*price;
you obviously have to adjust your return type as well:
public decimal SetDiscountPrice(){
return price = price - (decimal)10/100*price;
}
Important Information:
Maybe you should actually overthink your attempt a little bit. A method starting with "Set" sounds like it should be a property and I think it's definitely possible in your case. And are you sure you want your setter-method to change your value and return it at the same time? Maybe following could help you:
class YourClass{
public decimal Price {get; set;}
public decimal DiscountPrice => (decimal)10/100*Price;
}

How do i hold the correct output value without roundoff the double value in given program

Given the meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip), and tax percent (the percentage of the meal price being added as tax) for a meal, find and print the meal's total cost.
Condition: Be sure to use precise values for your calculations, or you may end up with an incorrectly rounded result!
Here is my Program:
static void Main(String[] args)
{
double mealCost=Convert.ToDouble(Console.ReadLine());
int tipPercent=Convert.ToInt32(Console.ReadLine());
int taxPercent=Convert.ToInt32(Console.ReadLine());
double tip,tax;
tip=(mealCost*(tipPercent/100));
tax=(mealCost*(taxPercent/100));
double totalCost=mealCost+tip+tax;
Console.WriteLine("The total meal cost is {0} dollars",totalCost);
Console.ReadLine();
}
But I had the output as 12.
My Expected output is 15.
If my sample input is 12.00 20 8
My calculation as tip=2.4 and tax=0.96, totalCost=15.36
and the rounded value is
(round)totalCost=15.
But the output came as 12.
How do I get the correct output in C#. Can anyone provide me some suggestions to resolve this issue.
What you have to do is, take tipPercent and taxPercent as double values or else implicitly convert them to double before processing division like the following:
tip = (mealCost * ((double)tipPercent / 100));
tax = (mealCost * ((double)taxPercent / 100));
Then you will get totalCost=15.36 for the input specified in the question. Much smarter solution is :
double mealCost, tipPercent, taxPercent;
Console.WriteLine("Enter values for Meal Cost, Tip percentage and tax percentage");
if (!double.TryParse(Console.ReadLine(), out mealCost))
{
Console.WriteLine("Invalid input for meal Cost");
}
if (!double.TryParse(Console.ReadLine(), out tipPercent))
{
Console.WriteLine("Invalid input for Tip percentage");
}
if (!double.TryParse(Console.ReadLine(), out taxPercent))
{
Console.WriteLine("Invalid input for Tip tax Percent");
}
double tip = (mealCost * (tipPercent / 100));
double tax = (mealCost * (taxPercent / 100));
double totalCost = mealCost + tip + tax;
Console.WriteLine("The total meal cost is {0}", totalCost.ToString("C0"));
Console.ReadLine();
First, please change your data type to decimal instead of double, more suitable for money related.
Second, when you do the calculation, C# will try to return with the same data type, which caused:
tip=(mealCost*(tipPercent/100)); // it will turn tipPercent/100 to int, which is 0
tax=(mealCost*(taxPercent/100)); // same here
You have many way to do it, like cast as double:
tip = (mealCost * ((double) tipPercent / 100));
State the 100 to 100D (tell c# it is double)
tip = (meanCost * (tipPercent / 100D));
Or, just use double / decimal for your tipPercent and taxPercent
double tipPercent = Convert.ToDouble(Console.ReadLine());
in division you should have at least one double to get answer in double very less change you need to make it work see bellow
static void Main(String[] args)
{
double mealCost=Convert.ToDouble(Console.ReadLine());
int tipPercent=Convert.ToInt32(Console.ReadLine());
int taxPercent=Convert.ToInt32(Console.ReadLine());
double tip,tax;
tip=(mealCost*(tipPercent/100.0));//change 100 to 100.0
tax=(mealCost*(taxPercent/100.0));//change 100 to 100.0
double totalCost=mealCost+tip+tax;
Console.WriteLine("The total meal cost is {0} dollars",totalCost);
Console.ReadLine();
}
Your problem is related to this two lines:
tip=(mealCost*(tipPercent/100));
tax=(mealCost*(taxPercent/100));
These define operations between integer and will return integers. Cast to double or declare 100 as double like this: 100d
You are getting 0 since you code divide an int value by an int value. The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. You can review how C# handles it here.
If you rewrite your tip, tax calculation with following.
tip = (mealCost * tipPercent / 100);
tax = (mealCost * taxPercent / 100);

Round to 25, 50, 75, 100

I'm not a Math person so I'm having a hard time to come up with a calculation to round the decimals to 25, 50, 75 and 100. And this will not be the typical round off because the decimals will not be decreased but only increased.
Example:
if 11.12, round to 11.25
if 11.34, round to 11.50
if 11.52, round to 11.75
if 11.76, round to 12.00
Here's my starting method:
public float RoundNearestCents(String price)
{
float srp;
return srp;
}
public float RoundNearestCents(double d)
{
return (double)(Math.Ceiling(d * 4)) / 4;
}
I suggest using types without floating point.
decimal RoundNearestCents(decimal price) {
// no problems with floating point as all calculations are exact
return Math.Floor((price * 100 + 24) / 25) * 25 / 100;
}
-- Why is your price string?
-- Because it's coming from a textbox.
I assume your textbox should support limiting your input to decimal numbers with at most 2 decimal places. So its value will be decimal already. However I don't know what is your application type. If you still want to accept string then consider using decimal.TryParse method to convert it to decimal.
My code may not be the best out there, but it will work.
In your function create a float and an int like so.
public float RoundNearestCents(String price)
{
float srp = float.Parse(price);
int srp1 = Int32.Parse(price);
if((srp-srp1)>=0.5)
srp1++;
else
return srp1;
return srp1;
}
The int would truncate out the decimal part, which is like flooring the price.
I would use something like this:
float RoundNearestCents(float price)
{
price*=(100/25.0); // now fractions are going away
if (price-floor(price)>=0.5) price++; // round up if fraction above 0.5
return floor(price)*(25.0/100.0); // cut of the fraction and restore original range
}
This is one way:
public decimal RoundNearestCents(decimal price)
{
decimal srp = price * 100;
decimal m = srp % 25;
srp = srp - m + (m > 0 ? 25 : 0);
return srp / 100;
}

Division returns zero

This simple calculation is returning zero, I can't figure it out:
decimal share = (18 / 58) * 100;
You are working with integers here. Try using decimals for all the numbers in your calculation.
decimal share = (18m / 58m) * 100m;
18 / 58 is an integer division, which results in 0.
If you want decimal division, you need to use decimal literals:
decimal share = (18m / 58m) * 100m;
Since some people are linking to this from pretty much any thread where the calculation result is a 0, I am adding this as a solution as not all the other answers apply to case scenarios.
The concept of needing to do calculations on various types in order to obtain that type as a result applies, however above only shows 'decimal' and uses it's short form such as 18m as one of the variables to be calculated.
// declare and define initial variables.
int x = 0;
int y = 100;
// set the value of 'x'
x = 44;
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0. The conversion to double happens
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );
// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
Because the numbers are integers and you perform integer division.
18 / 58 is 0 in integer division.
Whenever I encounter such situations, I just upcast the numerator.
double x = 12.0 / 23409;
decimal y = 12m / 24309;
Console.WriteLine($"x = {x} y = {y}");
double res= (firstIntVar * 100f / secondIntVar) / 100f;
when dividing numbers I use double or decimal , else I am getting 0 , with this code even if firstIntVar && secondIntVar are int it will return the expected answer
decimal share = (18 * 100)/58;
Solved: working perfectly with me
int a = 375;
int b = 699;
decimal ab = (decimal)a / b * 100;

Categories

Resources