mercredi 5 décembre 2018

JavaScript if-statement inside function to avoid division by zero NaN result?

I have this inside a function and the problem is one of the vars could be 0 and as we all know one can't divide by 0.

                    html += ('<div class="portlet banner-port" style="border-color: #2d0059;" class="panel-collapse collapse"> \
                            <div class="portlet-heading" style="background: linear-gradient(to right, rgba(0, 0, 0, 0.40) 0%, rgba(0, 0, 0, 0) 100%), #2d0059;"> \
                                <div class="portlet-title" style="color:#ffffff;"> \
                                    <h4> \
                                    <i class="fa fa-link fa-fw"></i> '+jstext.language.custom_direct_link+' <span style="float:right"><span>'+jstext.language.custom_raw_visits+': '+resp.link.hits+'</span> <span>'+jstext.language.custom_transactions+': '+resp.link.conv+'</span> <span>'+jstext.language.custom_earnings+': '+resp.link.earnings+' €</span>  <span>EPC: '+(resp.link.earnings / resp.link.hits * 100).toFixed(2)+' €</span></span> \
                                    </h4> \
                                </div> \
                                    <div class="portlet-body"><label>'+jstext.language.marketing_target_url+':</label> \
                                        <textarea style="font-weight:normal !improtant;" id="direct-link-'+resp.data.id+'" rows="1" class="form-control">'+resp.direct_url+'</textarea> \
                                    </div> \
                            </div> \
                        </div>')

So in this case the JSON response resp.link.hits could be 0 and then the EPC is, as one should expect - NaN. I am having some basic syntax issues here, as I see it. Where do I declare to show 0 instead of NaN in this part:

<span>EPC: '+(resp.link.earnings / resp.link.hits * 100).toFixed(2)+' €</span>

I tried a couple of things like:

<span>EPC: '+if( resp.link.hits === 0 ){0} else {(data.earnings / data.hits * 100).toFixed(2)}+' €</span>

But I can't make it show 0 instead of NaN when dividing by 0. Any ideas? Any help appreciated!!

Aucun commentaire:

Enregistrer un commentaire