简体   繁体   English

JavaScript数学,以.05为增量舍入到两位小数

[英]javascript math, rounding to two decimal places in .05 increments

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. 我已经阅读了许多文章,并且我确定答案在于实现toFixed()方法,但toFixed()

$('.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. 基本上,以上是对AMEX存款增加(或减去)2.5%的附加费,我希望将其四舍五入到最接近的两位十进制数。 Preferably in .05 increments. 最好以0.05为增量。

Help appreciated! 帮助赞赏!

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. 我认为发布者的意思是,某种货币以美分计算,但价格以x.00或x.05美分给出。 For example Swiss currency. 例如瑞士货币。

The solution, borrowed from RobG's answer with a little fix: 该解决方案是从RobG的答案中借来的,并做了一些修正:

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);
}

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 (ie, to two decimals)?" 如果您的问题是“我如何取v包含一个美元和美分金额的变量,并应用2.5%的AMEX附加费,结果四舍五入到最接近的美分(即,两位小数)?” 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. 请注意, toFixed返回字符串表示形式,但是它将为您进行舍入。

(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.) (关于您的“无附加费”功能,您无法删除以前乘以-0.025所附加的0.025附加费。将附加乘以1.025即可得到该附加费,因此将其除以1.025即可。)

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: 如果要输入的文本格式为“ 2.03”,则可以使用以下方法将其舍入到最接近的$ 0.05:

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. 字符串操作非常快速,并通过简单的加减运算来代替javascript乘法和十进制小数除法的不确定性。

eg borrowing from rfausak's answer: 例如,从rfausak的答案中借用:

// Returns string, remove ' + ''' to return number
function roundToFiveCents(v) {
  return (Math.round(v*20)/20).toFixed(2) + '';
}
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. 这个简单的函数非常适合四舍五入到x个位数。

How about the following javascript: 下列javascript怎么样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM