问题描述
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
| | . | |
,并且在每个html元素上单击时,我创建了名为number()
的函数
就是这样
number(number)
{
this.total_quantity_discount_price = this.total_quantity_discount_price+''+number;
this.total_quantity_discount_price = parseFloat(this.total_quantity_discount_price);
},
带有数字0123456789
的一切都很好,但是我遇到的.
问题如何将.
加到this.total_quantity_discount_price
我的意思是我该如何添加数字10.555或55.648等。
谢谢..
解决方法
使用Number
构造函数,如
this.total_quantity_discount_price = Number(this.total_quantity_discount_price+''+number);
let n=Number(4+'.'+5)
// the n is a number which you could add it to another
console.log(n)
console.log(n+1)
console.log(n-3)
,
您可以像这样使用+
运算符:
const n = '4' + '.' + '3' + '4';
console.log(+n);
console.log(+n + 1);
console.log(+n - 1);
您的功能将变为:
function number(number){
this.total_quantity_discount_price = +(this.total_quantity_discount_price + '' + number);
}
,
您可以将所有内容合并在一起,并使用let result = "";
let calc = document.getElementById("calculation");
let output = document.getElementById("result");
document.querySelectorAll("button").forEach(el => {
el.addEventListener("click",()=> {
result += el.innerHTML;
output.innerHTML = result;
})
})
function render() {
let calcResult = interprete(result);
output.innerHTML = calcResult;
}
function getResult() {
output.innerHTML = interprete(result);
}
function clearResult() {
output.innerHTML = "";
result = "";
}
function back () {
result = result.slice(0,-1);
output.innerHTML = result;
}
function interprete(str) {
return new Function(`return ${str}`)()
}
.buttonholder {
display: flex;
flex-flow: wrap;
width: 170px;
}
button {
display: block;
margin: 2px;
padding: 15px;
}
.box {
cursor: pointer;
background: black;
color: white;
padding: 10px;
margin: 10px;
}
#result {
background: green;
color: white;
padding: 10px;
}
<div class="buttonholder">
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
<button>8</button>
<button>9</button>
<button>.</button>
<button>+</button>
<button>-</button>
<button>*</button>
<button>/</button>
</div>
<div class="box" onclick="back()"> <== </div>
<p id="result"></p>
<div class="box" onclick="getResult()">=</div>
<p id="calculation"></p>
<div class="box" onclick="clearResult()">Clear</div>
{{1}}