Reputation: 3
This is a simple multiplication calculator which on typing automatically adds comma to separate groups of thousands. However it doesn't accept decimal value for example 1,778.23. Copy pasting it directly into the field works but can't type it. Any solution would be much appreciated.
function calculate() {
var myBox1 = updateValue('box1');
var myBox2 = updateValue('box2');
var myResult = myBox1 * myBox2;
adTextRes('result', myResult)
}
function updateValue(nameOf) {
var inputNo = document.getElementById(nameOf).value;
var no = createNo(inputNo);
adTextRes(nameOf, no);
return no;
}
function adTextRes(nameOf, no) {
var asText = String(no).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById(nameOf).value = asText;
}
function createNo(textin) {
return Number(textin.replace(/,/g, ""));
}
<table width="80%" border="0">
<tr>
<th>Box 1</th>
<th>Box 2</th>
<th>Result</th>
</tr>
<tr>
<td><input id="box1" type="text" oninput="calculate()" /></td>
<td><input id="box2" type="text" oninput="calculate()" /></td>
<td><input id="result" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
Upvotes: 0
Views: 65
Reputation: 370779
The problem is, in createNo
:
return Number(textin.replace(/,/g, ""));
A trailing period will just get discarded when converted to a Number
. There's no need for such a casting in the first place, though - just leave it off, and it'll work as expected:
function createNo(textin) {
return textin.replace(/,/g, "");
}
To prevent multiple decimal points from being entered, you can use another replace
in the same function:
.replace(/(\.\d*)\./, '$1')
function calculate() {
var myBox1 = updateValue('box1');
var myBox2 = updateValue('box2');
var myResult = myBox1 * myBox2;
adTextRes('result', myResult)
}
function updateValue(nameOf) {
var inputNo = document.getElementById(nameOf).value;
var no = createNo(inputNo);
adTextRes(nameOf, no);
return no;
}
function adTextRes(nameOf, no) {
var asText = String(no).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById(nameOf).value = asText;
}
function createNo(textin) {
return textin
.replace(/,/g, "")
.replace(/(\.\d*)\./, '$1')
}
<table width="80%" border="0">
<tr>
<th>Box 1</th>
<th>Box 2</th>
<th>Result</th>
</tr>
<tr>
<td><input id="box1" type="text" oninput="calculate()" /></td>
<td><input id="box2" type="text" oninput="calculate()" /></td>
<td><input id="result" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
Upvotes: 1