Plus operator problems in Jquery - javascript

I was trying with following script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#item1_number_1').keyup(function() {
var valone = $('#item1_number_1').val();
var valtwo = 5;
var total = ((valone) + (valtwo));
$('#item2_number_1').val(total.toFixed(2));
});
});
</script>
I do not get any result in the field. But when I assign multiple (*) instead of plus (+), I am getting result.
I cannot understand what the error is in "var total = ((valone) + (valtwo));"

You can only call toFixed on Numbers.
String * String will convert the strings to Numbers and multiply them giving you a Number.
String + String will concatenate the two Strings together giving you a String.
You need to convert the strings to Numbers manually before you try to add them together.
var total = (+valone) + (+valtwo);
Then Number + Number will add the two Numbers together giving you a Number.

The value of an input is always a string. "Adding" a string concatenates, giving another string. Strings do not have a toFixed method.
* however is unambiguously "multiply", giving a number and therefore a result.
var valone = parseFloat(document.getElementById('item1_number_1').value);

Use parseInt() to convert fetched value(valone ) to number, and calculate, something like this, please use this only when your number is not float(56.66),
var valone = parseInt($('#item1_number_1').val(), 10);
var valtwo = 5;
var total = ((valone) + (valtwo));
The fetched vaue is treated like string until you convert it into number.
UPDATE
After Archer pointed out, I came to know you are using toFixed() method, which supposed to expect float numbers. So in this case you should use parseFloat() as given below.
var valone = parseFloat($('#item1_number_1').val());

I think one of them is a string. Try parseInt(valone) to make it an int first.

The issue is the + operator can also be used to concat strings together. The * operator is ONLY for multiplication and therefore it implicitly converts your values to numbers.
So you either need to use parseInt, parseFloat, or Number to explicitly convert to a numeric type before using the + operator.

Related

How to get an 8 decimal output?

I am trying to get an 8 decimal output from the following function.
The following function multiplies an input by 2 and then updates this input with the wagerUpdate variable. I would like this outputted number to have 8 decimal places.
For example: if input number is 0.00000001 (this code is for a bitcoin website), then I would like output number to be 0.00000002. For some reason the code below is not working properly as the output number is in the format of 2e-8 without the .toFixed(8) code. Please help if you are able to. Thank you so much.
<script>
function MultiplyWagerFunction() {
var wager = document.getElementById("wagerInputBox").value;
var wagerUpdate = wager*2;
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
}
</script>
If you remove the + before wagerUpdate.toFixed(8) it should work fine. wagerUpdate has already be converted to a number when you multiplied it by 2 so there should be no need for the unary +
var a = "0.00000001";
var b = a*2;
console.log(b.toFixed(8));
console.log(+b.toFixed(8));
^ see the difference.
The reason it doesn't work is because what you are doing is equivalent to:
+(b.toFixed(8))
because of the precedence of the operators (member access . is higher than unary +). You are converting b to a string with .toFixed and then converting it back into a number with + and then converting it back into a string again! (this time with the default toString behavior for numbers giving you exponential notation)
Just remove + from +wagerUpdate.toFixed(8); and you would be good.
Instead of:
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
try:
document.getElementById("wagerInputBox").innerHTML = +wagerUpdate.toFixed(8);
Why I say so is may be when you set value, browser tries to convert to best possible outcome. But, inner HTML should take the string equivalent!

Javascript: using toLocaleString + Tofixed

I need to format a number for a project im working on at work, only problem is that I cant format it how i want.
I convert the number to a localestring using the toLocaleString method which gives me the commas but i also need decimal places, nothing i seem to do works.
var number = 123.322
number = parseFloat(number).toFixed(2) //123.22
number.toLocaleString() //123.22
The above code just returns the parsefloated number along with the tofixed decimal values but it doesn't add the commas.
How do i get a number to have two decimal places (when the value is 'xx.00') and also be comma separated. Is this possible in JavaScript?
You can give an object to .toLocaleString() which describes what you want:
var sNumber = (10123.322).toLocaleString(undefined,
{'minimumFractionDigits':2,'maximumFractionDigits':2});
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
Original:
const fNumber = 10123.322;
const sNumber = parseFloat(fNumber.toFixed(2)).toLocaleString();
console.log(sNumber);
The number is already in decimal/float format on the first line.
.toFixed(2) turns it into a string using fixed-point notation.
parseFloat() takes that string and turns it back into a float.
.toLocaleString() turns it into a string using the local format.
Just to do it in one line
var num = '12233.3366554';
num = parseFloat(parseFloat(num).toFixed(2)).toLocaleString('en-IN', { useGrouping: true });
Yes, it is possible using .toLocaleString, yo just need to specify the language, optionally you can specify decimals and currency. look at this example:
35000.2455.toLocaleString('en-IN', {minimumFractionDigits: 2, maximumFractionDigits: 2,style: 'currency', currency: 'USD' })
this returns $35,000.25
Number.toLocaleString works on a number, but toFixed returns a string.
Coerce the string back into a number first
var number = 123.322;
var string = parseFloat(number).toFixed(2);
var parsed = (+string).toLocaleString();
console.log(parsed);
In order to get commas you have to specify the locale .The locale en includes commas for the numbers. toFixed() Returns a string. toLocaleString() function commas works on a number not on a string.So parse the string to float.
var number = 1234567.322;
number = parseFloat(parseFloat(number).toFixed(2)).toFixed(2) ;
number=number.toLocaleString('en');
toLocaleString function provide number representation based on languages
var number = 3500.00;
if(Number.isInteger(number)){
var zeroappend= number.toLocaleString()+".00";
console.log(zeroappend);//3,500.00;
}else{
console.log(number.toLocaleString());
}

Converting Strings to Integer and get the persentage of two number

What I'm trying to do is to make a progress bar for donation. My html structure is:
<div class="hgoal" style="text-align: center;">My goal is to raise $<span id="mygoal">9,999.00</span></div>
<div class="donation-total">Total Donation<span id="total-donation">1,000.00</span></div>
my javascript so far is to get the innerHTML value of mygoal and total-donation.
var mygoal = document.getElementById("mygoal").innerHTML;
var totalgoal = document.getElementById("total-donation").innerHTML;
and I'm getting this as a result:
mygoal = "9,999.00";
total-donation = "1,000.00";
I believe this is a string and not an integer, and using parseInt() only give me the first digit number.
Can anyone give me an idea how can I make this into an integer that can use for computation? example:
mygoal + total-donation = 10,999.00
And also, any idea how can i get the percentage of this two varible?
Use .replace(/,/g,'') to replace commas, then you get the magic of type coercion to convert your string to a number during calculation...
var mygoal = document.getElementById("mygoal").innerHTML.replace(/,/g,'');
var totalgoal = document.getElementById("total-donation").innerHTML.replace(/,/g,'');
If you use + on strings, they will be appended to each other, but other mathematical operators (*/- etc...) will first coerce the strings into numbers. To force coercion, you can multiply by 1, or perhaps use Number("123123.123")...
Number(mygoal) + Number(totalgoal); // using addition, so coerce strings to numbers
(mygoal / total_donation) * 100; // does not need coercion
Your main issue is, that your numbers include colons. The parseFloat() call will work, once you replace these colons. You may use the following code to do so:
// define regexp to replace colons
var replaceColons = new RegExp(',', 'g');
// apply regex
num = num.replace(replaceColons, '');
mygoal=parseInt(mygoal.replace(/,/gi,"")) will give you mygoal=9999.
You should use parseFloat(), not parseInt() ...
More, you have to remove the commas from the string, since parseFloat() does not undertsand number formatting characters (like comma). So, for example:
mygoal = mygoal.replace(/,/g, '');
total_donation = total_donation.replace(/,/g, '');
To get the percentage of two numbers, use:
(mygoal / total_donation) * 100;
Note that in JavaScript you can't use 'minus' char (-) in variables names.
You could use for example 'underscore' char (_), or CamelCase, wich is the recommended style for variables in JavaScript.
You need to convert those Indian (maybe) numbers to valid Javascript numbers for the sum, then convert the output back to the initial format using Number.toLocaleString.
var mygoal = "9,999.00";
var total_donation = "1,000.00";
var total = Number((Number(mygoal.replace(/,/g, '')) + Number(total_donation.replace(/,/g, ''))).toFixed(2));
var finalResult = total.toLocaleString('en-IN',{minimumFractionDigits: 2 });
alert(finalResult);

Javascript is treating variables as Strings, why?

I have the variable y, which is a subtotal. Its value is different depending on what happens with the html, but throughout the script I declared it like this:
var y = 21.78;
etc. Why is it that on my last equation where I add up the total, it treats them as strings when I want to add the values?
var tax = (0.055*y).toFixed(2);
var totalprice = y+tax;
/* totalprice holds "21.781.20" instead of 22.98 */
According to:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed
toFixed() returns:
A string representation of number that does not use exponential
notation and has exactly digits digits after the decimal place.
thus, y+tax is cast to a string since one of the operands is a string.
In my opinion, this would make sense as Javascript's intrinsic numeric types do not have the ability to store a specific number of decimal place digits, so a string would be the most appropriate data structure to store this with.
I would advise you do all your addition before calling toFixed(), since the method is most suitable for formatting display output.
var taxRate = 0.055;
var subtotal = 21.78;
var tax = (taxRate * subtotal).toFixed(2),
totalprice = ((1+taxRate) * subtotal).toFixed(2);
document.write(totalprice);
The .toFixed() method returns a string. Try applying that method as the last step after all other calculations.
Here's a simple fix. Put '+' in front of the tax variable to convert it to a number.
var y = 21.78;
var tax = (0.055*y).toFixed(2);
var totalprice = y+ (+tax);
totalprice === 22.98;
If you don't want any rounding errors when you use toFixed, then include this re-implementation of it in your script.
http://bateru.com/news/2012/03/reimplementation-of-number-prototype-tofixed/
In my experience, if there's any chance available, Javascript will see the "+" sign as concatenate rather than addition. It's driven me nuts on more than one occasion. I will generally do this rather than chance concatenation:
var totalprice = parseInt(y)+parseInt(tax);
When letter replaces value, multiply with 1 when you're in need of +.
var totalprice = (y*1) + tax .
Other operands work fine, it's just the + operand that needs special treatment when variable replace value.

Decimal Value addition not working, returning string

I want to do some math like plus, minus etc. with decimal values.
So i wrote two functions;
function to_decimal(i){
var $dec = parseFloat(i);
return $dec.toFixed(2);
}
function calc_price(){
var $t = $('#sub_total .total').text();
var $total = to_decimal($t);
$('#price_list ul li').each(function(){
var $p = to_decimal($(this).find('.item_price').text());
$total = $total + $p;
});
$t = $('#sub_total .total').text($total);
}
But these functions not working correctly i think because the result is returning string like 0.0010.30
Where is the problem?
You need to add a + infront of that statement and you're fine:
return +$dec.toFixed(2);
That will convert the string into a number. If the string cannot get converted, it'll return the NaN value.
Instead of:
return $dec.toFixed(2);
Do:
return Math.round($dec*100)/100;
The toFixed method returns a string. Any mathematical operation that doesn't affect the output can be used to convert the string to a number (except addition, whose operator unfortunately doubles as the string concatenation operator):
$dec.toFixed(2) - 0
$dec.toFixed(2) / 1
$dec.toFixed(2) * 1
+$dec.toFixed(2)
These are the fastest methods. However, if speed is not a concern (and it probably isn't when performing a small number of operations) then the clearest, most-readable method to convert a string to a number is the Number constructor:
Number($dec.toFixed(2))
Edit: The performance information above may no longer be universally true. The Number constructor is indeed considerably slower than each of the alternatives in IE 7.0 and Firefox 5, but actually performs the best in Chrome 12.0.742.
See:
http://jsperf.com/js-string-to-number-conversion

Categories

Resources