Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: why does this produce and ugly string??? I would like currency

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?

like image 222
Hcabnettek Avatar asked Jul 31 '09 18:07

Hcabnettek


People also ask

What is this ${} in JavaScript?

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}. `

Can you manipulate a string in JavaScript?

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.

How do you strip text in JavaScript?

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.

Which is better HTML or JavaScript?

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.


2 Answers

.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;
like image 130
Quentin Avatar answered Sep 20 '22 15:09

Quentin


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());
like image 31
dcharles Avatar answered Sep 20 '22 15:09

dcharles