Multiple order quanity x price and show decimal two places - javascript

How do I get the javascript and php to display two decimal places after calculation. Right now it works fine but no decimal places, just whole numbers
php********
<td> width="3"><input type="text" name="order_quan" /></td>
<td><input type="text" name="Price" /></td>
<td><font color="yellow"><span class=Price></span></td>
Java Script********
<script>
$('input[name=order_quan], input[name=Price]').keyup(function() {
var divParent = $(this).closest('div');
var order_quan = $('input[name=order_quan]', divParent).val()-0;
var Price = $('input[name=Price]', divParent).val()-0;
if (order_quan >= 0 && Price >= 0)
$('span.Price', divParent).text(order_quan*Price);
});
</script>

You can use .toFixed(2);
(order_quan * Price).toFixed(2);

Here's the basics
String((order_quan*Price * 100)>>0).replace(/(\d{2}$)/,'.$1');
//shift it 2 decimal places left, floor it, and add '.' before the last two digits

Related

How to calculate sum in th:each thymeleaf?

I have a list of persons that I need to display, and for each person there is an input for age.
I need to sum the ages when im writing; I mean if I have 5 persons when I'm on the 5th record, i need the total of previous 4 ages like this one : Calculate sum from number type input fields by javascript
this is my code :
<tr th:each="person : ${persons}">
<td th:text="${person.first_name}"></td>
<td th:text="${person.last_name}"></td>
<td th:text="${person.phone}"></td>
<td><input id="age" class="form-control"
type="text" name="age" th:field="*{ages}">
</td>
</tr>
Total : <input type="text" name="total" id="total"/>
I did this js script, but in total it gives me only the value of first line !!!! Any help ?
<script type="text/javascript">
$(document).ready(function(){
$("#age").each(function() {
$(this).on('input', function(){
calculateSum();
});
log.console("sum :"+sum);
});
});
function calculateSum() {
var sum = 0;
$("#age").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
$("#sum").html(sum.toFixed(2));
}
</script>
put all of the ages in array
On every place you want to show the sum of the previous ages:
2.1. slice the array from 0 to the place of the current value (beacuse slice(0,x) actually slicing the array from 0 to x-1).
2.2 execute the reduce function on the sliced array, you can see an example here: https://www.w3schools.com/jsref/jsref_reduce.asp

Sum numbers with JavaScript doesn't work properly "Intl.NumberFormat"

I have page with table of products and for each product there is a price.
When I change the qty it gets the total price...
But I have this problem:
When the numbers are lower then "1,000", the sum is ok.
ex:
prod 1: 200
prod 2: 200
prod 3: 500
total: 900
But when the numbers are greater then "1,000", the comma is the problem. I get a wrong answer.
ex:
prod 1: 200
prod 2: 1,200
prod 3: 300
total: 501
When I remove the "Intl.NumberFormat" from the total of each product, I get the right answer, but for some cases I get numbers like this: "1.000031545",
which I don't need. I only need the first 2 digit after the dot.
CODE: (simplefied)
<table>
<tr>
<td style="text-align: center;">
<label for="prod[<?php echo $prodid; ?>]"><input class='qty' style="font-size: 12px;" type="text" name="qty_<?php echo $prodid; ?>" placeholder="qty" minlength="1" maxlength="3" size="2"></label>
</td>
<td class='price'>
<?php echo $prodprice; ?>
</td>
<td width="40" class="sum">0</td>
</tr>
<tr>
<td colspan="3">
<span class="output"></span>
</td>
</table>
<script type="text/javascript">
function getTotal(){
var total = 0;
$('.sum').each(function(){
total += parseFloat(this.innerHTML);
});
$('#total').text(total);
givenNumber = total;
nfObject = new Intl.NumberFormat('en-US');
output = nfObject.format(givenNumber);
document.querySelector('.output').textContent = total;
}
getTotal();
$('.qty').keyup(function(){
var parent = $(this).parents('tr');
var price = $('.price', parent);
var sum = $('.sum', parent);
var value = parseInt(this.value) * parseFloat(price.get(0).innerHTML||0);
givenNum1 = value;
nfObj = new Intl.NumberFormat('en-US');
outpu = nfObj.format(givenNum1);
sum.text(outpu);
getTotal();
})
</script>
Referencing the MDN Web Docs
If parseFloat encounters a character other than a plus sign (+), minus
sign (- U+002D HYPHEN-MINUS), numeral (0–9), decimal point (.), or
exponent (e or E), it returns the value up to that character, ignoring
the invalid character and characters following it.
You can remove the comma by using replace() and then parse it afterwards to get the right value.
let str = "1,200"
let newStr = str.replace(/,/g,"");
console.log(`Without replace ${parseFloat(str)}`);
console.log(`With replace ${newStr}`);
parseFloat stops parsing at the first invalid character. , is not a valid character to parseFloat.
You can remove the ,:
total += parseFloat(this.textContent.replace(/,/g, ""));
Note that I also switched from innerHTML to textContent.
Also note that I used a regular expression with the g ("global") flag, since .replace(",", "") would only replace the first comma (so 1,200,300 would fail). Or in modern environments you can use replaceAll but it's relatively new (though easily polyfilled):
total += parseFloat(this.textContent.replaceAll(",", ""));
For this I'd just use the regular expression.

Input number does not limit decimal when "0" is typed

I have a scenario where the HTML input field must take only 16 digit where 6 of its digits will be allocated for decimal places, but one strange thing happend in the code below is, when I add "0" at the end of decimal values, the digits are not being restricted and it keeps increasing. Is there anything that I'm missing out here?
<input type="number" name="val" min=0 max=9999999999.999999 step=".000001" save="" oninput="validity.valid ? this.save = value : value = this.save;"
Resolved the issue with the following code
<input type="number" name="val" min=0 max=9999999999.999999 step=".000001" save="" oninput="validity.valid && ((value.toString()).split('.')[1] === undefined || ((value.toString()).split('.')[1].length < 6)) ? this.save = value : value = this.save"/>

How can I perform math on last x characters of string and update text box on the fly?

I have an app where a user scans or types in a starting barcode, and the ending barcode is automatically calculated based on a quantity value.
It works fine when the starting barcode is entirely numeric, it does the math and includes leading zeroes so the end code is the correct length.
My problem is that some small percentage of the barcodes are not entirely numeric.
The barcodes are 14 characters long. The last 5 characters will always be numeric and quantities will rarely exceed a few hundred and never go high enough that we spill into the 6th digit.
I'm not a javascript expert by any means, and just getting what I have now working strained my skills -- I'm hoping the community here can help me out :)
Here's the code I'm working with:
$(document).ready(function() {
//leading zero fill function for barcodes
function pad(num, size) {
var s = "00000000000000" + num;
return s.substr(s.length - size);
}
//Function to do BC math: starting number + quantity -1 (since it's inclusive) = end.
function updateCode() {
var quantity = $(this).closest('tr').find('.quantity').val();
var barstart = $(this).closest('tr').find('.barstart').val();
var end = pad(parseInt(barstart, 10) + parseInt(quantity - 1, 10), 14);
$(this).parent().next().find('.barend').val(end);
}
$(document).on("change, keyup", ".barstart", updateCode);
});
Edit Trying to insert the HTML again:
<script src="//code.jquery.com/jquery-1.7.2.min.js"></script>
<table id="formtable">
<tr>
<td><input class="quantity" size="6" id="qty_1" name="qtyid_1" value="123" type="text"></td>
<td><input class="barstart" size="15" maxlength="14" id="barstartid_1" name="barstart_1" value="" placeholder="Barcode Start" type="text"></td>
<td><input class="barend" size="15" maxlength="14" id="barendid_1" name="barend_1" value="" placeholder="Barcode End" type="text"></td>
</tr>
</table>
Here's a jsfiddle: https://jsfiddle.net/g1p2xh6y/1/
The users can live without it, but it'll save them some headaches (and help me make a good impression - this is a new gig) if I can get it working, so I greatly appreciate any help the community can offer :)
Thanks!
Many thanks to #admcfajn - I didn't know the slice() function existed, and that resolved it for me. I had to move the zero padding to the suffix, and remove it from the end value, but since it's pulling the prefix instead of doing math, that's no problem.
Here's the updated function:
function updateCode() {
var quantity = $(this).closest('tr').find('.quantity').val();
var barstart = $(this).closest('tr').find('.barstart').val();
var barprefix = barstart.slice(0,barstart.length-5);
var barendsuffix = pad(parseInt(barstart.slice(-5),10)+parseInt(quantity-1,10),5);
$(this).parent().next().find('.barend').val(barprefix+barendsuffix);
}

replace characters in price calculation JS

I'm creating a script for percentage calculation on my e-commerce, but I have a problem.
If i use use characters such as: ", . %" the price value says "NaN".
So I made this:
<input type="text" name="cost" onkeyup="disc()"> <br><br>
<input type="text" name="discount" id="prized" onkeyup="updateInput()">
<input type="text" name="price" value="">
<script>
function updateInput(){
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
}
function disc(){
if($("#prized").val().length > 1) {
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
}
}
</script>
How can I replace the characters when they are inserted on cost value or discount value?
I did some research, and I found an interesting function: .replace
I have no idea how to use it in my script.
Someone can help me reach my goal?
You should have to replace special characters , and & like this
var price = $(".price").val().replace(/,/g, "").replace("%", "")
This replace(/,/g, "") will replace multiple replace of comma ,
Ex. 1,00,000 be 100000
Why not validate your user input prior to calling your function? create a regex to only allow the characters you want. As it is your user can input any character they want in the input box. Probably a good idea to limit that.
I don't know whether this is the requirement, any way replace work like below,
var test = "90.56%";
test = test.replace(/[.%]/g, "");
//test will be "9056"

Categories