سؤال

Trying to make sense of some of the JavaScript Math functions and processing the output properly as strings.

What I need is the following for a 'pay in three instalments' function:

  1. Divide a price in 3 (a/b/c)
  2. Set them to two decimal places
  3. Round down b and c
  4. Add the remainders of b & c to a as a needs to be highest price, then b & c equal.
  5. Input a into div class Instal1

Here's the code (did it all in variables) will this work? Nothing coming out in the jsfiddle result window...

http://jsfiddle.net/hslincoln/8e5Vr/17/

$(document).ready(function () {

var handyTotal = jQuery(".price").text().replace(/\u00A3/g, '');

var aPrice = handyTotal / 3; // takes basket total & /3
var aPrice2dec = aPrice.toFixed(2); // converts to number with 2 decimal places
var bPrice = handyTotal / 3;
var bPrice2dec = bPrice.toFixed(2);
var cPrice = handyTotal / 3;
var cPrice2dec = cPrice.toFixed(2);

var bPriceFloored = Math.floor(bPrice2dec); // rounds down number 
var cPriceFloored = Math.floor(cPrice2dec);
var overflowbPrice = bPrice2dec - bPriceFloored; // finds amount to add to a
var overflowcPrice = cPrice2dec - cPriceFloored;
var calcaPrice = $(".Instal1").text(aPrice2dec + overflowbPrice + overflowcPrice); // adds b+c to a
});
هل كانت مفيدة؟

المحلول 3

With a bit of fiddling and help above, here is the answer:

http://jsfiddle.net/hslincoln/8e5Vr/36/

jQuery(document).ready(function () {

var handyTotal = jQuery(".price").text().replace(/\u00A3/g, '');

var aPrice = handyTotal / 3; // takes basket total & /3
var aPrice2dec = parseFloat(aPrice.toFixed(3)); // converts to number with 3 decimal places
var bPrice = handyTotal / 3;
var bPrice2dec = parseFloat(bPrice.toFixed(3));
var cPrice = handyTotal / 3;
var cPrice2dec = parseFloat(cPrice.toFixed(3));  

var bPriceFloored = Math.floor(bPrice2dec); // rounds down number 
var cPriceFloored = Math.floor(cPrice2dec);
var overflowbPrice = bPrice2dec - bPriceFloored; // finds amount to add to a
var overflowcPrice = cPrice2dec - cPriceFloored;
var calcaPrice = jQuery(".Instal1").text((parseFloat(aPrice2dec) + parseFloat(overflowbPrice) + parseFloat(overflowcPrice)).toFixed(2)); // adds b+c to a

var bPriceFlooredDiv = jQuery(".Instal2").text(Math.floor(bPrice2dec));
var cPriceFlooredDiv = jQuery(".Instal3").text(Math.floor(cPrice2dec));

Thanks all!

نصائح أخرى

You have simple reference errors:

bPricedec and cPricedec is not defined. Fix them to bPrice2dec and cPrice2dec respectively.

Always keep an eye on the JavaScript console for error reports ;)

You mistyped your variables in 3 places. Mistyped variables are: bPricedec and cPricedec

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top