var total = 0;
$(".amount").each(function () {
var value = $(this).val();
value = (value.length < 1) ? 0 : value;
var tmp = parseFloat(value).toFixed(2);
total += tmp;
});
$(".total").text(total);
I am trying to loop through some text boxes and sum up their values. This produces a nasty string. What am I missing?? if I put 8 in the first textbox total text ends up as " 08.000.000.000.00". What am I doing wrong? I would like to format as currency but if not, at least just a two decimal number. Any pointers?
With template literals, an expression can be embedded in a placeholder. A placeholder is represented by ${} , with anything within the curly brackets treated as JavaScript and anything outside the brackets treated as a string: const method = 'interpolation' const dynamicString = `This string is using ${method}. `
Strings are objects within the JavaScript language. They are not stored as character arrays, so built-in functions must be used to manipulate their values. The functions provide various ways to access the contents of a string variable.
String strip() in JavaScript We can strip a string using trim() method and can remove unnecessary trailing and leading spaces and tabs from the string.
JavaScript simply adds dynamic content to websites to make them look good. HTML work on the look of the website without the interactive effects and all. HTML pages are static which means the content cannot be changed. It adds interactivity to web pages to make them look good.
.toFixed converts the object from a Number to a String.
Leave the full values in place and only convert using .toFixed at the very end
$(".total").text(total.toFixed(2));
Alternatively, convert the string back to a number.
total = total + + tmp;
Just FYI, there is an excellent mathematical aggregation plugin for jQuery: jQuery Calculation
Using that plugin may also indirectly solve your issue.
It's usage would reduce your script to:
$('.total').text($('.amount').sum());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With