1

I need to calculate percentage of some not equal number. I am counting percentage using parseFloat, but it's work only for rounded numbers like 2000, or 200 which gives me 20% and 2%. I's not working for 2200 or 220 to reach 2.2% or 22.2%.

$(document).on('keyup', '.js-baOfferPrice.percentage', function(e) {
    var s, target = $(e.target);
    var p = $('.js-baAppPrice').text();

    s = parseFloat(parseInt(target.val(), 10) * 100) / parseInt(p, 10);

    target.val() === "" ? target.val("") : target.val(Math.round(s).toFixed(0));
});

Can anybody help?

easwee
  • 15,757
  • 24
  • 60
  • 83
Lukas
  • 7,384
  • 20
  • 72
  • 127

2 Answers2

2

Change .toFixed(0) to .toFixed(1) and remove the Math.round()

This line:

target.val() === "" ? target.val("") : target.val(Math.round(s).toFixed(0));

will become:

target.val() === "" ? target.val("") : target.val(s.toFixed(1));

Reference: toFixed
Stack Overflow Reference: Math.round(num) vs num.toFixed(0)

Community
  • 1
  • 1
97ldave
  • 5,249
  • 4
  • 25
  • 39
  • I's not changing anything, after this i have still 0.0 when i'm trying to type 2200 as a number. – Lukas Dec 23 '14 at 10:56
  • Sorry, my mistake, you need to remove the Math.round() as well. This is removing the decimal. – 97ldave Dec 23 '14 at 11:02
1

Don't call Math.round(s), since that removes the fractional part of the number. Just use toFixed, and specify the number of decimal places there. It will round that digit.

if (target.val() !== "") {
    s = parseFloat(parseInt(target.val(), 10) * 100) / parseInt(p, 10);
    target.val(s.toFixed(1));
}
Barmar
  • 741,623
  • 53
  • 500
  • 612