我想最多舍入2位小数,但只在必要时.
输入:
10
1.7777777
9.1
Run Code Online (Sandbox Code Playgroud)
输出:
10
1.78
9.1
Run Code Online (Sandbox Code Playgroud)
我怎么能这样做__CODE__?
我有这行代码将我的数字四舍五入到小数点后两位.但是我得到这样的数字:10.8,2.4等.这些不是我的两位小数的想法,所以我如何改进以下内容?
Math.round(price*Math.pow(10,2))/Math.pow(10,2);
Run Code Online (Sandbox Code Playgroud)
我想要10.80,2.40等数字.使用jQuery对我很好.
我有以下JavaScript语法:
var discount = Math.round(100 - (price / listprice) * 100);
Run Code Online (Sandbox Code Playgroud)
这可以达到整数.如何以小数点后两位返回结果?
你可以将javascript中的数字舍入到小数点后的1个字符(正确舍入)吗?
我尝试了*10,round,/ 10但它在int的末尾留下了两位小数.
当数字变大时,JavaScript会将大型INT转换为科学记数法.我怎样才能防止这种情况发生?
请考虑以下代码:
for (var i=0;i<3;i++){
var num = i + 0.50;
var output = num + " " + Math.round(num) + " " + num.toFixed(0);
alert(output);
}
Run Code Online (Sandbox Code Playgroud)
在Opera 9.63中我得到:
0.5 1 0
1.5 2 2
2.5 3 2
在FF 3.03我得到:
0.5 1 1
1.5 2 2
2.5 3 3
在IE 7中我得到:
0.5 1 0
1.5 2 2
2.5 3 3
注意粗体结果.为什么会出现这种不一致的情况?这是否意味着toFixed(0)应该避免?将数字舍入到最接近的整数的正确方法是什么?
javascript的"Number.toFixed"的默认实现似乎有点破碎.
console.log((8.555).toFixed(2)); // returns 8.56
console.log((8.565).toFixed(2)); // returns 8.57
console.log((8.575).toFixed(2)); // returns 8.57
console.log((8.585).toFixed(2)); // returns 8.59
Run Code Online (Sandbox Code Playgroud)
我需要一种比这更一致的舍入方法.
在8.500和8.660之间的范围内,以下数字不能正确舍入.
8.575
8.635
8.645
8.655
Run Code Online (Sandbox Code Playgroud)
我已经尝试按如下方式修复原型实现,但它只有一半.任何人都可以建议任何可以使其更一致地工作的变化吗?
Number.prototype.toFixed = function(decimalPlaces) {
var factor = Math.pow(10, decimalPlaces || 0);
var v = (Math.round(this * factor) / factor).toString();
if (v.indexOf('.') >= 0) {
return v + factor.toString().substr(v.length - v.indexOf('.'));
}
return v + '.' + factor.toString().substr(1);
};
Run Code Online (Sandbox Code Playgroud) 使用toFixed时遇到舍入错误:
我使用toFixed(2)了我的数值计算,但是对于少数情况,舍入结果并不像预期的那样.
假设它toFixed(2)应用于值17.525然后它给出结果17.52,如果它被应用5.525然后它给出结果5.53.
在后一种情况下,舍入结果是准确的,因此您可以建议需要做什么来获得准确的舍入结果,如在后一种情况下.或者你可以建议一个替代这个toFixed函数来获得正确的舍入结果?
我用了两种方法:
Number.prototype.myRound = function (decimalPlaces) {
var multiplier = Math.pow(10, decimalPlaces);
return (Math.round(this * multiplier) / multiplier);
};
alert((239.525).myRound(2));
Run Code Online (Sandbox Code Playgroud)
数学警报应该是239.53它的239.52输出.所以我尝试使用.toFixed()功能&我得到了正确的答案.
但是,当我试图得到239.575它的答案再次给出错误的输出.
alert((239.575).toFixed(2));
Run Code Online (Sandbox Code Playgroud)
这里输出应该是239.58它的给予239.57.
此错误在最终输出中产生一点差异.所以有人可以帮我解决这个问题吗?
我需要使用javascript将小数值四舍五入到小数位.
防爆,:
16.181 to 16.18
16.184 to 16.18
16.185 to 16.19
16.187 to 16.19
Run Code Online (Sandbox Code Playgroud)
我找到了一些答案,但大多数答案都没有完成16.185到16.19.