我正在尝试使用JavaScript在计算器中显示十进制值。
如果我单击计算器中的任何按钮,则按钮值将从右至左添加到十进制值中,并且应该在屏幕上显示。
例如: The default value is 0.00 if i click 2, it should be 0.02 and if i click 3, it should be 0.23 and if i click 4, it should be 2.34 and if i click 5, it should be 23.45 and so on.
答案 0 :(得分:2)
您可以尝试:
let number = 0;
// Returns the new value in case you need it to display in console
// and updates the number variable with the new value.
function addNumberRightToLeft(value) {
number = ((number * 10) + (value / 100)).toFixed(2);
return number;
}
console.log(addNumberRightToLeft(5)); // Shows '0.05' in console and updates number variable, so it is now '0.05'.
// or
addNumberRightToLeft(5); // Does not print to console but updates number variable, so it is now '0.55'.
甚至使用ES6箭头功能且没有副作用(如Nika所建议的那样):
const addNumberRightToLeft = (p, v) => ((p * 10) + (v / 100)).toFixed(2);
其中p
是返回的最后一个值,而v
是要添加的内容。实际中:
let number = 0;
number = addNumberRightToLeft(number, 5); // 0.05
number = addNumberRightToLeft(number, 5); // 0.55
答案 1 :(得分:0)
如下所示:resultNum应该首先初始化为0.00;
line-height