jquery - javascript math, rounding to two decimal places in .05 increments - Stack Overflow

I apologise in advance. I've read thru a number of post and I'm sure the answer lies in imple

I apologise in advance. I've read thru a number of post and I'm sure the answer lies in implementing the toFixed() method, but can't work out how.

$('.addsurcharge').click(function() {               
    $('span.depositamount').text(function(i,v) {
        return Math.round(parseInt(v * 100, 10) * 0.025) / 100 + (v * 1);
    });      
});

$('.nosurcharge').click(function() {            
    $('span.depositamount').text(function(i,v) {
        return Math.round(parseInt(v * 100, 10) * -0.025) / 100 + (v * 1);
    });      
});

Basically, the above is adding (or subtracting) a 2.5% surcharge for AMEX deposits and I want it to round up to the nearest two decimal amount. Preferably in .05 increments.

Help appreciated!

I apologise in advance. I've read thru a number of post and I'm sure the answer lies in implementing the toFixed() method, but can't work out how.

$('.addsurcharge').click(function() {               
    $('span.depositamount').text(function(i,v) {
        return Math.round(parseInt(v * 100, 10) * 0.025) / 100 + (v * 1);
    });      
});

$('.nosurcharge').click(function() {            
    $('span.depositamount').text(function(i,v) {
        return Math.round(parseInt(v * 100, 10) * -0.025) / 100 + (v * 1);
    });      
});

Basically, the above is adding (or subtracting) a 2.5% surcharge for AMEX deposits and I want it to round up to the nearest two decimal amount. Preferably in .05 increments.

Help appreciated!

Share edited Sep 22, 2011 at 6:58 Michael J. Barber 25.1k9 gold badges71 silver badges91 bronze badges asked Sep 22, 2011 at 5:51 BrendanBrendan 111 silver badge3 bronze badges 5
  • 1 Not entirely sure what you mean by "in .5 increments". Can you elaborate? – GregL Commented Sep 22, 2011 at 5:55
  • I don't understand your requirement to have "two decimal" with ".5 increments". Wouldn't the latter be 1, 1.5, 2, 2.5, etc? Can you explain that a bit better with some examples of before and after rounding? Also, why are you using parseInt(v * 100,10)? If v is a decimal it will multiple by 100 and round down to the nearest integer (because parseInt throws away everything after the first non-digit); if v is an integer it is pointless; if v is not a number it won't work at all. – nnnnnn Commented Sep 22, 2011 at 5:56
  • Thanks for the reply. My mistake, should have written .05 inrements. This is for an Australian site and all currency here is in .05 increments (5c is the smallest coin). Not sure about the second question, I have inherited the above code mostly as-is and am just trying to fix up the decimal issue. Happy to change if there is a more practical solution - you may have guessed, this is not my area of expertise. – Brendan Commented Sep 22, 2011 at 6:02
  • 1 As an Australian I have to dispute your assertion that all currency here is in .05 increments. All cash payments are in .05 increments because our smallest denomination coin is the 5c, but any electronic transactions, or old-school paper-based credit card or cheque transactions (including, obviously, AMEX transactions) are to the nearest cent. Do not even think about rounding to nearest 5 cents unless your customer is paying cash. – nnnnnn Commented Sep 22, 2011 at 6:11
  • I take your point and don't disagree. In this particular implementation tho, the amount is for a small deposit and usually in whole dollar amounts. I simply wanted to avoid fractional decimals for the sake of simplified accounting and user experience. Thanks for the feedback. – Brendan Commented Sep 22, 2011 at 6:49
Add a ment  | 

5 Answers 5

Reset to default 2

The easiest way for currency is to work in the minor units, then round and convert to major units only at the end. So for a system with dollars and cents, work in cents until the end, then convert to dollars. If the text to be input is of the format "2.03", then it can rounded it to the nearest $0.05 using something like:

function roundToFiveCents(v) {

  // Turn dollars into cents and convert to number
  var len;
  v = v * 100;

  // Get residual cents
  var r = v % 5;

  // Round to 5c
  if (r) {
    v -= (r == 1 || r == 2)? r : r-5;
  }

  // Convert to string
  v = v + '';
  len = v.length - 2;

  // Return formatted string
  return v.substring(0, len) + '.' + v.substring(len);
}

That can be more concise, but I can't see the point, it would only server to obfuscate. String manipulation is very fast and replaces the uncertainty of javascript multiplication and division of decimal fractions with simple addition and subtraction.

e.g. borrowing from rfausak's answer:

// Returns string, remove ' + ''' to return number
function roundToFiveCents(v) {
  return (Math.round(v*20)/20).toFixed(2) + '';
}

If your question is "How do I take v, a variable that contains a dollar-and-cents amount, and apply a 2.5% AMEX surcharge with the result rounded to the nearest cent (i.e., to two decimals)?" Then you can try this:

return (v * 1.025).toFixed(2);

If you have a variable surcharge try this:

var surcharge = 0.025; // or whatever percentage applies

return (v * (1 + surchage)).toFixed(2);

Note that toFixed returns a string representation, but it does the rounding for you.

(Regarding your "nosurcharge" function, you can't remove a 0.025 surcharge that was applied previously by multiplying by -0.025. You apply the surchage by multiplying by 1.025, so you remove it by dividing by 1.025.)

Although the post is a bit old, the question isn't. I think what the poster meant was, that some currency calculate with cents, but the prices are given in x.00 or x.05 cents. For example Swiss currency.

The solution, borrowed from RobG's answer with a little fix:

function roundToFiveCents(v) {
    var len;
    // Format to 2 numbers after decimal point an turn dollars into cents
    v = v.toFixed(2) * 100;

    // Get residual cents
    var r = v % 5;

    // Round to 5c
    if (r) {
        v -= (r === 1 || r === 2) ? r : r - 5;
    }

    // Convert to string
    v = v + '';
    len = v.length - 2;

    // Return formatted string
    return v.substring(0, len) + '.' + v.substring(len);
}

How about the following javascript:

function my_round(x) {
    x *= 20;
    x = Math.ceil(x);
    return x / 20;
}
var amount = 3.37;
alert(my_round(amount));
var n = 8.22354;
roundx(n, 3)

function roundx(num, decPlace) {
  return Math.round(num * Math.pow(10, decPlace))/Math.pow(10, decPlace);
}

This simple function works well for rounding to x number of places.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745067821a4609361.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信