Javascript VS PHP取整 [英] Javascript VS PHP rounding

查看:51
本文介绍了Javascript VS PHP取整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用PHP和javascript整数的方式时遇到一些问题.我正在使用PHP的round函数和此javascript函数:

I am having some problems with the way PHP and javascript round numbers. I am using PHP's round function and this javascript function:

function roundNumber(number, decimals) {     
    var newnumber = new Number(number+'').toFixed(parseInt(decimals));
    var value = parseFloat(newnumber);
    return value;
}

我要四舍五入的数字是43.65 * 2.5 + 40%,当使用计算器完成时= 152.775或在PHP中四舍五入= 152.78.

The number i am trying to round is 43.65 * 2.5 + 40% which when done using a calculator = 152.775 or when rounded in PHP = 152.78.

在javascript中,当我执行console.log时,数字为152.774999999998,当使用上述函数取整后,得出的数字为152.77

In javascript when i do a console.log the number is 152.774999999998 and when rounded with the above function gives me 152.77

感谢您对解决此问题的任何帮助

Any help to reslove this issue is greatly appreciated

推荐答案

请查看这里是一个示例

function roundNumber(number, decimals) {
  decimals = parseInt(decimals,10);
  var dec = Math.pow(10,decimals)
  console.log(dec,parseFloat(number)*dec);
  number=""+Math.round(parseFloat(number)*dec+.0000000000001); // fixed the .X99999999999
  return parseFloat(number.slice(0,-1*decimals) + "." + number.slice(-1*decimals))     
}


var val = 43.65 * 2.5;
    val+= val*0.40

console.log(val+' ~= 152.78? --> '+roundNumber(val,2).toFixed(2));
console.log('15.803 ~= 15.80? --> '+roundNumber(15.803,2).toFixed(2));
console.log('15.805 ~= 15.81? --> '+roundNumber(15.805,2).toFixed(2));
console.log('14.803 ~= 14.80? --> '+roundNumber(14.803,2).toFixed(2));
console.log('0.575 ~=  0.58? --> '+roundNumber(0.575,2).toFixed(2));

这篇关于Javascript VS PHP取整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆