Объясните пож. просто чудеса происходят))) Вопрос по js
На скриншоте явно видно, что результат 0.3, т.е все работает как нужно. Но, если вырезаю и вставляю это же условие в this.dasplayValue = ..... , то, при уже выдает NaN, хотя условие тоже. Подскажите пож. в чем ошибка, и как сделать, чтоб калькулятор работал корректно. Обычные числа считал без остатка, а дробные показывал без знаменитой всем ошибки 0. 3000000000000000004
calc() {
this.displayValue = eval(Math.floor(this.displayValue * 100) / 100);
// console.log(eval(Math.floor(this.displayValue * 100) / 100));
},
Vue.createApp({
data() {
return {
item: ['-', 9, 8, 7, '+', 6, 5, 4, '.', 3, 2, 1, 0, '*', '/'],
displayValue: '',
};
},
methods: {
buttonShow(num) {
this.displayValue += num;
},
clear() {
this.displayValue = '';
},
calc() {
this.displayValue = eval(Math.floor(this.displayValue * 100) / 100);
// console.log(eval(Math.floor(this.displayValue * 100) / 100));
},
back() {
if (this.displayValue) {
this.displayValue = this.displayValue.substring(
0,
this.displayValue.length - 1
);
}
},
percent() {
this.displayValue = this.displayValue / 100;
},
},
}).mount('#app');
.grid{
max-width: 360px;
margin: 50px auto;
padding: 20px;
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(4, 1fr);
background-color: #233244;
user-select: none;
}
.item {
padding: 15px;
border: none;
color: white;
font-size: 28px;
background-color: #31455e;
cursor: pointer;
transition: .3s ease-in;
}
.item:hover{
transform: scale(1.05);
background-color: turquoise;
}
.input {
background-color: #31455e;
grid-column: 1/-1;
height: 50px;
outline: none;
text-align: right;
padding-right: 10px;
font-size: 28px;
color: white;
}
.equally{
grid-column: 4/-1;
grid-row: 5/7;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id='app'>
<div class="grid">
<input class="input" type="text" readonly v-bind:value="displayValue">
<button class="item" @click="clear()">C</button>
<button class="item back" @click="back()">⇽</button>
<button class="item" @click="percent()">%</button>
<button class="item" v-for="i of item" @click="buttonShow(i)">{{i}}</button>
<button class="item equally" @click="calc()">=</button>
</div>
</div>
<script src="https://unpkg.com/vue@next"></script>
<script src="main.js"></script>
</body>
</html>
Ответы (1 шт):
Всему виной некорректная проверка.
Так, сначала вычисляется выражение
this.displayValue = eval(this.displayValue);
И лишь затем происходит вывод
console.log(eval(Math.floor(this.displayValue * 100) / 100));
В данном случае this.displayValue - уже число, а не строка, поэтому все отрабатывает корректно.
В случае без console.log
this.displayValue = eval(Math.floor(this.displayValue * 100) / 100);
this.displayValue - это строка, и результат умножения может варьироваться в зависимости от конкретного значения.
Так как, например, строка 0.1+0.2 - не может привестись к числу, результат умножения - NaN.
Для решения, достаточно сначала вычислить выражение и лишь затем округлять
Math.floor(eval(this.displayValue) * 100) / 100
Пример
Vue.createApp({
data() {
return {
item: ['-', 9, 8, 7, '+', 6, 5, 4, '.', 3, 2, 1, 0, '*', '/'],
displayValue: '',
};
},
methods: {
buttonShow(num) {
this.displayValue += num;
},
clear() {
this.displayValue = '';
},
calc() {
this.displayValue = Math.floor(eval(this.displayValue) * 100) / 100;
},
back() {
if (this.displayValue) {
this.displayValue = this.displayValue.substring(
0,
this.displayValue.length - 1
);
}
},
percent() {
this.displayValue = this.displayValue / 100;
},
},
}).mount('#app');
.grid {
max-width: 360px;
margin: 50px auto;
padding: 20px;
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(4, 1fr);
background-color: #233244;
user-select: none;
}
.item {
padding: 15px;
border: none;
color: white;
font-size: 28px;
background-color: #31455e;
cursor: pointer;
transition: .3s ease-in;
}
.item:hover {
transform: scale(1.05);
background-color: turquoise;
}
.input {
background-color: #31455e;
grid-column: 1/-1;
height: 50px;
outline: none;
text-align: right;
padding-right: 10px;
font-size: 28px;
color: white;
}
.equally {
grid-column: 4/-1;
grid-row: 5/7;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id='app'>
<div class="grid">
<input class="input" type="text" readonly v-bind:value="displayValue">
<button class="item" @click="clear()">C</button>
<button class="item back" @click="back()">⇽</button>
<button class="item" @click="percent()">%</button>
<button class="item" v-for="i of item" @click="buttonShow(i)">{{i}}</button>
<button class="item equally" @click="calc()">=</button>
</div>
</div>
<script src="https://unpkg.com/vue@next"></script>
<script src="main.js"></script>
</body>
</html>
