如何将两个带小数的数字相加?

时间:2017-09-19 11:05:37

标签: javascript html

我想用小数加两个数字,这是我的代码:

function myNumbers() {
   var val1 = parseInt(document.getElementById("value1").value);  
   var val2 = parseInt(document.getElementById("value2").value);
   alert(val1+val2);
}
value1 = <input type="text" id="value1" name="value1" value="1"/>
value2 = <input type="text" id="value2" name="value2" value="2"/>
<input type="button" name="Sumbit" value="Click here" onclick="javascript:myNumbers()"/>

3 个答案:

答案 0 :(得分:3)

var data = [{ "Assessment": { "AssessmentId": 3, "AssessmentText": "CRM", "Measures": { "MeasureId": 6, "MeasureText": "CF", "SubMeasures": { "SubMeasureId": 12, "SubMeasureText": "TNCF", "Apps": { "Name": "BOT", "Rating": 0 } } } } }, { "Assessment": { "AssessmentId": 3, "AssessmentText": "CRM", "Measures": { "MeasureId": 6, "MeasureText": "CF", "SubMeasures": { "SubMeasureId": 12, "SubMeasureText": "TNCF", "Apps": { "Name": "CPSM", "Rating": 0 } } } } }, { "Assessment": { "AssessmentId": 3, "AssessmentText": "CRM", "Measures": { "MeasureId": 6, "MeasureText": "CF", "SubMeasures": { "SubMeasureId": 16, "SubMeasureText": "TNCF", "Apps": { "Name": "DEA", "Rating": 0 } } } } } ]; function elemExists(array, property, val) { for (var i = 0; i < array.length; i++) { if (array[i][property] && array[i][property] === val) { return i; } } return -1; } var result = {}; data.forEach(function(d, idx) { if (idx == 0) { let s = d; let subMeasures = []; let apps = []; apps.push(d.Assessment.Measures.SubMeasures.Apps); s.Assessment.Measures.SubMeasures.Apps = apps; subMeasures.push(d.Assessment.Measures.SubMeasures); s.Assessment.Measures.SubMeasures = subMeasures; result = Object.assign({}, s); } else { let found = elemExists(result.Assessment.Measures.SubMeasures, "SubMeasureId", d.Assessment.Measures.SubMeasures.SubMeasureId); if (found >= 0) { result.Assessment.Measures.SubMeasures[found].Apps.push(d.Assessment.Measures.SubMeasures.Apps); } else { result.Assessment.Measures.SubMeasures.push(d.Assessment.Measures.SubMeasures); } } }); console.log(result);会得到一个完整的数字。请改用parseInt,这将获得数字及其小数值。

parseFloat
function myNumbers() {
   var val1 = parseFloat(document.getElementById("value1").value);  
   var val2 = parseFloat(document.getElementById("value2").value);
   alert(val1+val2);
}

答案 1 :(得分:0)

尝试 parseFloat()而不是 parseInt()将其转换为float val

答案 2 :(得分:0)

如果您不使用浮点数添加toFixed,则添加0.1 + 0.2的结果将为0.30000000000000004

&#13;
&#13;
function myNumbers() {
   var val1 = parseFloat(document.getElementById("value1").value);  
   var val2 = parseFloat(document.getElementById("value2").value);
   alert((val1+val2).toFixed(1));
}
&#13;
value1 = <input type="text" id="value1" name="value1" value="1"/>
value2 = <input type="text" id="value2" name="value2" value="2"/>
<input type="button" name="Sumbit" value="Click here" onclick="javascript:myNumbers()"/>
&#13;
&#13;
&#13;