按值或按百分比计算百分比

时间:2016-03-02 22:25:29

标签: jquery

我有3个输入字段来计算价格和折扣百分比。第一个字段是正常价格。我想要做的是: 如果用户更改百分比值,将计算折扣价格(2位小数),如果用户更改折扣价格,将计算百分比。

目前我只计算了百分比:

function calculatePrice() {
    var percentage = $('input[name=\'percentage\']').val(),
        price = $('input[name=\'price\']').val(),
        calcPrice = price - ( (price/100) * percentage ),
        discountPrice = calcPrice.toFixed(2);
    $('input[name=\'discount\']').val(discountPrice);
}
function calculatePerc() {
    var discountPrice = $('input[name=\'discount]\']').val(),
        price = $('input[name=\'price\']').val(),
        calcPerc = (price/100) * (price-discountPrice),
        discountPerc = calcPerc.toFixed();
    $('input[name=\'percentage\']').val(discountPerc);
}

我的HTML:

<input type="text" name="price" value="1000">
<input type="text" name="percentage" onkeyup="calculatePrice()">
<input type="text" name="discount" onkeyup="calculatePerc()">

这是我的小提琴:https://jsfiddle.net/90bo9okg/

3 个答案:

答案 0 :(得分:6)

fmLoan
// Reusable helper functions
const calculateSale = (listPrice, discount) => {
  listPrice = parseFloat(listPrice);
  discount  = parseFloat(discount);
  return (listPrice - ( listPrice * discount / 100 )).toFixed(2); // Sale price
}
const calculateDiscount = (listPrice, salePrice) => {
  listPrice = parseFloat(listPrice);
  salePrice = parseFloat(salePrice);
  return 100 - (salePrice * 100 / listPrice); // Discount percentage
}

// Our use case
const $list = $('input[name="list"]'),
      $disc = $('input[name="disc"]'), 
      $sale = $('input[name="sale"]'); 
    
$list.add( $disc ).on('input', () => { // List and Discount inputs events
  let sale = $list.val();              // Default to List price
  if ( $disc.val().length ) {          // if value is entered- calculate sale price
    sale = calculateSale($list.val(), $disc.val());
  }
  $sale.val( sale );
});

$sale.on('input', () => {      // Sale input events
  let disc = 0;                // Default to 0%
  if ( $sale.val().length ) {  // if value is entered- calculate the discount
    disc = calculateDiscount($list.val(), $sale.val());
  }
  $disc.val( disc );
});

// Init!
$list.trigger('input');

答案 1 :(得分:0)

function calculatePrice() {
    var percentage = $('input[name=\'percentage\']').val(),
    price = $('input[name=\'price\']').val(),
    calcPrice = price - ((price / 100) * percentage),
    discountPrice = calcPrice.toFixed(2); 
    $('input[name=\'discount\']').val(discountPrice);
}

function calculatePerc() {
    var discountPrice = $('input[name=\'discount\']').val(),
    price = $('input[name=\'price\']').val(),
    calcPerc = (price - discountPrice) * 100 / price,
    discountPerc = calcPerc.toFixed(2);
    $('input[name=\'percentage\']').val(discountPerc);
}

答案 2 :(得分:0)

对于那些正在寻找小型,快速,简单的javascript代码来计算百分比并将其四舍五入的人:

var percentage = Math.round(((currentValue / goalValue) * 100)) +"%";

当小数返回“ 1”时,它将返回“ 100”。