【发布时间】:2015-12-26 12:13:33
【问题描述】:
自从我使用 jQuery 以来已经有好几年了,我确信我遗漏了一些明显的东西,但我无法弄清楚我的价值观发生了什么。
我有几个文本框和一个多选。文本框收集:重量、水分百分比和填充方块数。
多选具有关于每平方平方英尺的建筑特定信息。有些正方形是偶数,例如 22 平方英尺。其他的,保留两位小数,即 21.88。
当我用字符串进行计算时,我的数字回来得很奇怪。将我的变量按执行顺序记录到控制台后,我可以看到我的值正在做两件事之一。它们要么被四舍五入,要么被截断以删除小数。
这是我正在使用的代码:
$(document).ready(function(){
$('#btn_calculate').click(function(){
// This is the 'Truck Weight' text box
var TruckWeight = parseInt($('#input-number-weight').val(), 10);
console.log('Truck Weight :' + TruckWeight + ' .');
// This is the moisture percentage text box
var Moisture = parseInt($('#input-number-moisture').val(), 10);
console.log('Moisture:'+ Moisture +' .');
//This is the number of squares filled out, squares text box
var Squares = parseFloat($('#input-number-squares').val());
//I am not sure if this is necessary.
var ParseSquares = parseFloat(Squares);
console.log('ParseSquares: '+ ParseSquares +' .');
// Trying to prohibit the function from rounding the strings down/up
var Double = parseInt($('#select-doubles option:selected').val(), 10);
console.log('Double: '+ Double +' .');
<!-- testing percentages -->
var number = TruckWeight;
console.log('Number : '+number+' .');
var percentX = (100 - Moisture) - 1;
console.log('PercentX : '+percentX+' .');
var result;
console.log('Result :'+ result +' .');
function percentCalculation(a, b){
var c = (parseFloat(a)*parseFloat(b))/100;
return Math.round(c);
}
<!-- take the moisture percent out of 100 and multiply it by the weight of the truck -->
result = percentCalculation(number, percentX); //calculate percentX% of number
console.log(result);
console.log('Result :'+ result +' .');
var dry_matter = TruckWeight * result;
console.log('Dry Matter: '+ dry_matter +' .');
var squares_square_feet = (Squares * Double);
console.log('Squares Square Feet : ' + squares_square_feet +' .');
var dry_weight = dry_matter/squares_square_feet;
console.log('Dry Weight: ' + dry_weight + ' .');
});
});
细分是针对这个特定项目的:
var Double = parseInt($('#select-doubles option:selected').val(), 10);
select-doubles 是一个选择框,它的每个值都设置在所选房间的特定平方英尺上。例如,选项 1 的值为 21.9 平方英尺。选项 2 将有 21.84 平方英尺。
我遇到的问题是这个字符串会截断小数点,这把我的数学计算搞砸了。
我确信我可能做错了,或者以一种不太理想的方式。我喜欢批评和有益的指导。如果有人有任何想法可以缓解我在小数方面遇到的问题,我完全赞成。
我试过的是这个块:
//I am not sure if this is necessary.
var ParseSquares = parseFloat(Squares);
console.log('ParseSquares: '+ ParseSquares +' .');
// Trying to prohibit the function from rounding the strings down/up
var Double = parseInt($('#select-doubles option:selected').val(), 10);
console.log('Double: '+ Double +' .');
一些谷歌搜索引导我尝试这些方法,但结果是一样的。
感谢您的帮助!
【问题讨论】:
-
你能提供一个工作小提琴吗?
-
正如 Nathan 建议的那样,
parseInt()肯定会吞下你的小数。 -
不需要小提琴,切换到 parseFloat 就可以了!我曾尝试过 parseFloat,但愚蠢地不在适当的字符串上。感谢@Nathan P,一切都按预期工作。
标签: javascript java jquery html