-1

I can't figure out why I am getting this divide by zero exception. I'm very new to programming in general and can't figure out what I'm doing wrong. Sorry for the long code, I think I've removed about as much as possible and have it still give the exception. Here is the C# code...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;


namespace CalculationApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MainPage : ContentPage
    {
    public MainPage()
    {
        InitializeComponent();
        BreakEvenCalculation();
    }
    private void BreakEvenCalculation()
    {
        var purchaseprice = Decimal.Parse(PurchasePriceEntry.Text);
        var purchaseweight = Decimal.Parse(PurchaseWeightEntry.Text);
        var purchasefreight = Decimal.Parse(PurchaseFreightEntry.Text);
        var medicineimplants = Decimal.Parse(MedicineImplantsEntry.Text);
        var costofgain = Decimal.Parse(CostOfGainEntry.Text);
        var poundstillsell = Decimal.Parse(PoundsTillSellEntry.Text);
        var deathloss = Decimal.Parse(DeathLossEntry.Text);
        var saleweight = Decimal.Parse(SaleWeightEntry.Text);
        var salefreight = Decimal.Parse(SaleFreightEntry.Text);
        var breakeven = Decimal.Parse(BreakEvenEntry.Text);

        var purchasedollars = purchaseprice * purchaseweight;
        var feedcost = costofgain * poundstillsell;
        poundstillsell = saleweight - purchaseweight;

        var costs = (purchasedollars + purchasefreight + medicineimplants + feedcost + deathloss + salefreight);
        breakeven = costs / saleweight;             //throws exception.... System.DivideByZeroException: Attempted to divide by zero
        //breakeven = costs / (saleweight + 1);       //correctly equals 1.111302549965541
        //breakeven = costs * saleweight;           //correctly equals 2338125.00
        //breakeven = saleweight;                   //correctly equals 1450.00
        //breakeven = costs;                        //correctly equals 1612.50
        ////////////breakeven should equal  1.112068965517241
        BreakEvenEntry.Text = breakeven.ToString();
    }
    private void PurchasePriceEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void PurchaseWeightEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void PurchaseFreightEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void MedicineImplantsEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void CostOfGainEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void PoundsTillSellEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void DeathLossEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void SalePriceEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void SaleWeightEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void SaleFreightEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
}

And here is the xaml code...

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="CalculationApp.MainPage"
         xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:CalculationApp"
         xmlns:customentry="clr-namespace:CustomEntry">

<StackLayout Padding="0" BackgroundColor="AliceBlue" Orientation="Vertical">

    <Label Text="CalculationApp" TextColor="Black" FontAttributes="Italic" FontSize="Large" TextDecorations="Underline" Scale="1.5"
           Margin="0,15,0,10" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" VerticalOptions="CenterAndExpand"/>

    <Grid ColumnSpacing="0" RowSpacing="5">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width=".6*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <Label Text="Purchase Price" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="0" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap"/>
        <Label Text="Purchase Weight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="1" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Purchase Freight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="2" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Medicine/Implants" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="3" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Cost of Gain" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="4" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Pounds Till Sell" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="5" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Death Loss" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="6" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Sale Price" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="7" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Sale Weight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="8" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Sale Freight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="9" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />

        <Entry x:Name="PurchasePriceEntry" Text="{Binding Source={x:Reference PurchasePriceStepper}, Path=Value}" 
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="0" HorizontalTextAlignment="Center" Keyboard="Numeric" ReturnType="Next" VerticalOptions="End" MaxLength="5"
                             TextChanged="PurchasePriceEntry_Completed"/>
        <Entry x:Name="PurchaseWeightEntry" Text="{Binding Source={x:Reference PurchaseWeightStepper}, Path=Value}" 
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="1" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
                             TextChanged="PurchaseWeightEntry_Completed" />
        <Entry x:Name="PurchaseFreightEntry" Text="{Binding Source={x:Reference PurchaseFreightStepper}, Path=Value}" 
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="2" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
                             TextChanged="PurchaseFreightEntry_Completed" />
        <Entry x:Name="MedicineImplantsEntry" Text="{Binding Source={x:Reference MedicineImpantsStepper}, Path=Value}"  
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="3" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center" 
                             TextChanged="MedicineImplantsEntry_Completed" />
        <Entry x:Name="CostOfGainEntry" Text="{Binding Source={x:Reference CostofGainStepper}, Path=Value}"  
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="4" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center" 
                             TextChanged="CostOfGainEntry_Completed" />
        <Entry x:Name="PoundsTillSellEntry" Text="1000" TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory"  TranslationX="3"
                             Grid.Column="1" Grid.Row="5" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center" IsEnabled="False" />
        <Entry x:Name="DeathLossEntry" Text="{Binding Source={x:Reference DeathLossStepper}, Path=Value}"  
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="6" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
                             TextChanged="DeathLossEntry_Completed" />
        <Entry x:Name="SalePriceEntry" Text="{Binding Source={x:Reference SalePriceStepper}, Path=Value}"  
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="7" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
                             TextChanged="SalePriceEntry_Completed" />
        <Entry x:Name="SaleWeightEntry" Text="{Binding Source={x:Reference SaleWeightStepper}, Path=Value}"  
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="8" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
                             TextChanged="SaleWeightEntry_Completed" />
        <Entry x:Name="SaleFreightEntry" Text="{Binding Source={x:Reference SaleFreightStepper}, Path=Value}" 
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="9" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
                             TextChanged="SaleFreightEntry_Completed" />

        <Stepper x:Name="PurchasePriceStepper" Grid.Column="2" Grid.Row="0" HorizontalOptions="Center" VerticalOptions="Center"  Scale=".75" TranslationX="3" Maximum="5" Minimum=".01" Increment=".01" Value="1.75" />
        <Stepper x:Name="PurchaseWeightStepper" Grid.Column="2" Grid.Row="1" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="2000" Minimum="1" Increment="1" Value="550"/>
        <Stepper x:Name="PurchaseFreightStepper"  Grid.Column="2" Grid.Row="2" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="100" Minimum="0" Increment=".25" Value="10"/>
        <Stepper x:Name="MedicineImpantsStepper" Grid.Column="2" Grid.Row="3" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="500" Minimum="0" Increment=".25" Value="25.00"/>
        <Stepper x:Name="CostofGainStepper" Grid.Column="2" Grid.Row="4" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="3" Minimum="0" Increment=".01" Value="0.65"/>
        <Stepper x:Name="DeathLossStepper" Grid.Column="2" Grid.Row="6" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="500" Minimum="0" Increment="1" Value="20"/>
        <Stepper x:Name="SalePriceStepper" Grid.Column="2" Grid.Row="7" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="5" Minimum="0" Increment=".01" Value="1.25"/>
        <Stepper x:Name="SaleWeightStepper" Grid.Column="2" Grid.Row="8" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="5000" Minimum="0" Increment="5" Value="1450.00"/>
        <Stepper x:Name="SaleFreightStepper" Grid.Column="2" Grid.Row="9" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="100" Minimum="0" Increment=".25" Value="10"/>
    </Grid>

    <Grid Padding="10" ColumnSpacing="5" RowSpacing="10" VerticalOptions="FillAndExpand">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Label Text="Break Even" x:Name="BreakEvenLabel" TextColor="Black" FontSize="Medium" FontAttributes="Bold" Grid.Column="0" Grid.Row="0"  HorizontalTextAlignment="Center" VerticalOptions="Center" LineBreakMode="NoWrap" />
        <Label Text="Profit" TextColor="Black" FontSize="Medium" FontAttributes="Bold" Grid.Column="1" Grid.Row="0" HorizontalTextAlignment="Center" VerticalOptions="Center" LineBreakMode="NoWrap" />
        <Entry x:Name="BreakEvenEntry" Text="125" FontSize="Large" TextColor="Black" Grid.Column="0" Grid.Row="1" FontAttributes="Bold" BackgroundColor="Ivory" IsEnabled="False" HorizontalTextAlignment="Center" VerticalOptions="Center" />
        <Entry x:Name="ProfitEntry" TextColor="Black" FontSize="Large" Grid.Column="1" Grid.Row="1" FontAttributes="Bold" BackgroundColor="Ivory" IsEnabled="False" HorizontalTextAlignment="Center" VerticalOptions="Center" />
    </Grid>
</StackLayout>
</ContentPage>

The exception happens on this line in C#...

breakeven = costs / saleweight;

As you can see, I've tried changing the code several different ways to try to figure out whats going on. In my mind, to get the divide by zero exception, the saleweight has to be zero but if I change the code to simply read...

breakeven = saleweight;

The Xamarin.Forms BreakEvenEntry gives me the correct sale weight...so it isn't zero right??

What am I missing? What am I doing wrong??

Thanks for the help in advance!!

StevenB
  • 39
  • 1
  • 10
  • 2
    Can you provide a [mcve]? – ProgrammingLlama Mar 19 '19 at 02:22
  • I would have to assume your `SaleWeightEntry.Text` contents a zero?? – SushiHangover Mar 19 '19 at 02:23
  • 2
    You are dividing by zero, just debug your code, work out why, and fix it. this is truly a debugging problem – TheGeneral Mar 19 '19 at 02:29
  • 3
    **[How to use the Step Debugger built into VS](https://msdn.microsoft.com/en-us/library/y740d9d3.aspx)** – Ňɏssa Pøngjǣrdenlarp Mar 19 '19 at 02:36
  • Ok. When debugging(not through form output) I do get zero(I'm learning!). My code can't really be broken down to upload just part as all the controls are connected... My xamarin forms entries get their values from steppers using binding, so they aren't expressly given a value at the start. Could that be why? – StevenB Mar 19 '19 at 02:45
  • Have you tried to parse it this way : decimal saleweight = decimal.Parse(SaleWeightEntry.Text, CultureInfo.InvariantCulture); – Pooja Kamath Mar 19 '19 at 03:07
  • Possible duplicate of [Divide by zero error, how do I fix this?](https://stackoverflow.com/questions/160141/divide-by-zero-error-how-do-i-fix-this) – mjwills Mar 19 '19 at 03:35
  • The main problem is that values used in the calculation are pulled from the entry control instead of the source of the value, which is the stepper control. Change the method to pull the values from the stepper controls and that will fix the problem. Like this: var purchaseprice = PurchasePriceStepper.Value; – StevenB Mar 22 '19 at 04:37

1 Answers1

1

'Cost' is being created as a float or double and needs to be explicitly defined as decimal to match your parsed decimal variables.

decimal costs = (purchasedollars + [...]

Here is a link on integer vs float division for C#:

"If one of the operands is decimal, another operand can be neither float nor double, because neither float nor double is implicitly convertible to decimal. You must explicitly convert the float or double operand to the decimal type."

(Conversely to the above suggestion, you may consider parsing your variables as doubles or floats. Same result: float division instead of integer division.)

I attempted to reproduce your error, but was unable. I, however, was reminded of a time in Python 2.7 where I found a similar error.

MonteCarloSims
  • 1,751
  • 1
  • 7
  • 19
  • I switched the parsing to doubles instead of decimal and cast 'cost' to a double as well and that fixed my problem. Thank!! – StevenB Mar 19 '19 at 03:55