在 jquery 中对最终输出进行四舍五入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13644341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:49:55  来源:igfitidea点击:

Round up final output in jquery

jquerymathrounding

提问by Andy Holmes

I have the following code. Works beautifully apart from i want the final tinstotal variable to be rounded up to the nearest 1 (2.04 being rounded up to 3 etc)

我有以下代码。除了我希望最终的 tinstotal 变量四舍五入到最接近的 1(2.04 被四舍五入到 3 等)之外,效果很好

$(document).ready(function(){

// Animate logo
$('#Logo').hide().fadeIn(800);

// Calculation Scripts
// Square Metres
var output = $('#SquareMetres'),
    tinoutput = $('#Tins'),
    priceoutput = $('#Price');
$('input[type="text"]').keyup(function() {
var width = parseFloat( $('#width').val()),
    height = parseFloat( $('#height').val()),
    result = height * width / 10000,
    finalresult = result.toFixed(2);
if (isNaN(result)) return;

output.text(finalresult);

// Tins
var tinmetres = 32.5,
    tinprice = 18.23,
    tinsresult = finalresult / tinmetres;
    tinstotal = tinsresult.toFixed(2);

tinoutput.text(tinstotal);

var price = tinstotal * tinprice,
    totalprice = price.toFixed(2);

priceoutput.text('£'+totalprice)

});
});

the script is active here at http://andyholmes.me/sitewizard/index.htmlin the red box near the bottom. Hope you guys can help, thanks!

该脚本在http://andyholmes.me/sitewizard/index.html底部附近的红色框中处于活动状态。希望大家帮帮忙,谢谢!

回答by Kami

tinstotal = Math.ceil(tinsresult);
tinoutput.text(tinstotal);

Math.ceil()will round to the next whole number

Math.ceil()将四舍五入到下一个整数

回答by Phoenix

use javascript Math.round()

使用 javascript Math.round()

ex: 
var a = Math.round(2.60);
var b = Math.round(-2.60);
var c = Math.round(2.49);

Result : 
alert(a); => 3
alert(b); => -3
alert(c); => 2

Hope is helps you.

希望对你有帮助。

回答by chrisvillanueva

use javascript's Math.ceil() method to round numbers up.

使用 javascript 的 Math.ceil() 方法将数字向上舍入。

you can view information about this method here:

您可以在此处查看有关此方法的信息:

http://www.w3schools.com/jsref/jsref_ceil.asp

http://www.w3schools.com/jsref/jsref_ceil.asp

回答by James South

I would imagine you are looking for Math.ceil()

我想你正在寻找Math.ceil()