How to concatenate . (dot) with number in javascript

Viewed 456

hi ive created visual calc using html and its looks like this ..

| 1  | 2  | 3 | 
| 4  | 5  | 6 | 
| 7  | 8  | 9 | 
|    | .  |   |

and ive created function called number() on click on each html element and this is it

number(number)
{
    this.total_quantity_discount_price = this.total_quantity_discount_price+''+number;
    this.total_quantity_discount_price = parseFloat(this.total_quantity_discount_price);
},

with numbers 0123456789 everything is working fine but my problem with the . how can i add . to this.total_quantity_discount_price i mean how can i add the number 10.555 or 55.648 ect .. thanks ..

3 Answers

Use Number constructor like

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)

You can use the + operator like this :

const n = '4' + '.' + '3' + '4';

console.log(+n);
console.log(+n + 1);
console.log(+n - 1);

You function will become something like :

function number(number){
  this.total_quantity_discount_price = +(this.total_quantity_discount_price + '' + number);
}

You can concat everything together and parse it with new Function()

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>

Related