This is the Jquery codeļ¼
function Totalprice()
{
var unitprice=$('#unitpay').val();
var quota=$('#readers').val();
var totalprice=unitprice*quota;
$('#totalprice').text('$'+totalprice);
}
When the value of readers is 67 and the unitpay is 0.3, it calculates the total price and displays $20.099999999999998 , not $20.1. What's wrong? If I want it to display $20.1 instead of $20.099999999999998, how can I rewrite the code?
How about this:
$('#totalprice').text('$'+totalprice.toFixed(1));
or:
$('#totalprice').text('$'+totalprice.toFixed(2));
to show it as an actual dollar amount.
As your enthusiastic commentators pointed out, it's a floating point error. The quick and easy solution is to use a rounding method like toFixed().
Just use .toFixed(2). (link)
The problem is that computers can't represent some numbers exactly (they're finite, and operate in binary), so stuff like this happens.
Javascript has some pretty severe floating point issues. Try typing 0.1+0.2 in your Firebug console sometime for some fun.
This isn't an issue with jQuery. As has been mentioned above, use toFixed().
Related
I got a variable Javascrpit which has a number as a string in this case 0.84. I'm trying to convert it into a float but when I try to it appears a 0 as float instead the 0.84.
I'm using this:
var pot="0.84";
var asd = parseFloat(pot);
console.log(asd);
EDIT:
This is not exactly the example. I recover data from the HTML and it works for other numbers but not for this. It is difficult to explain my problem exactly. It is a lot of code and works for other numbers so don't know exactly.
Your input is not "0.84". If you test with that, you will get the correct answer. Your input has something else inside, like spaces, for example:
"0 .84"
This should be the solution:
parseFloat(pod.replace(/ /g, ""))
I have tried this example on my end and it completely worked. However, you can try to instead input the string value directly into the parse float() function and it should print our your expected value. If you still want to assign the parsefloat() to a variable, then try to either rewrite the code or re-open your IDE because the code should work.
var pot = "0.84"
console.log(parseFloat(pot))
or you can just write it in one line
console.log(parseFloat("0.84"))
I've avoided asking this question here as I know many have in the past. I've spent some time during the last few days trying to find a solution/figure out how the toFixed() method works. I've read a lot of questions on this site and tutorials on others but I'm still not getting it.
I have several text fields with the class, ".entry". A dollar amount is supposed to go here. When people type the following (examples):
1.2
5
6.35
8.
I need them to change to:
1.20
5.00
6.35
8.00
In other words, add the trailing zeros. I know this is accomplished through the toFixed() method but I'm completely at a loss. I can't get it to work.
I have a script I found that totals all the text fields in a DIV elsewhere on the page and I notice that it uses the toFixed() method:
$("#total").html(sum.toFixed(2).replace(/(^\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,'));
}
I tried using that same code here so the zeros could display in the text field:
$('.entry').keyup(function(){
var str = this.value.replace(/(^\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1');
if (str!=this.value) this.value = str;
});
It doesn't work.
I'm new to Jquery and Javascript so I realize I'm probably missing something obvious. Most of the tutorials I've read set the variable in the code and then use "document.write" to display the variable with the correct number of zeros:
Example:
document.write( 1.1.toFixed(2) + '<br>' );
But this isn't what I'm looking for. I need it to show up in the text field.
Thanks in advance!
A few things:
Use the change event instead of keyup. If you use keyup, the text wil change every time the user tries to type something, which is an annoying user experience.
Consider using an input of type number with a step of 0.1.
With those in mind, I'd do something like this:
$('.entry').change(function(){
// parse the typed value as a floating point number
var num = parseFloat(this.value);
// ensure there are two decimal places
this.value = num.toFixed(2);
});
Note that if the user types something with more than two decimal places, the value will be rounded.
Example: http://jsfiddle.net/jndt1e02/
So. I'm trying to subtract large integers. 76561198060995608 - 76561197960265728 = 100729880 type numbers. (I'm converting a 64 bit to a 32 bit) Vbscript and JS both give 100729888.
I would love to be able to do it in vbscript, but I'm either doing something wrong with cdbl (returns 100729888) or ccur (Overflow: 'ccur' error happens) or it can't be done the way I'm trying.
I've tried implementing JS libraries (bignum, bignumber) and they also haven't returned the correct number, again, maybe because of my error. BigNumber returns 100729890.
Big number code as follows:
$(document).ready(function(){
var x = new BigNumber(76561198060995608).subtract(new BigNumber(76561197960265728))
alert(x)
})
So...what am I doing wrong? Am I making a stupid mistake? I don't feel like this should take the 6+ hours it's taken me so far.
Any suggestions or help would be greatly appreciated. Thanks!
The problem is that when you try
new BigNumber(76561198060995608)
you're still relying on the JavaScript runtime to parse and represent that number before it calls the "BigNumber" constructor. I'm pretty sure you can pass a string to that constructor:
new BigNumber("76561198060995608")
and that should give you a fighting chance.
This is by far the strangest error I've ever seen.
In my program I have one variable called avgVolMix. It's a decimal variable, and is not NaN (console.log(avgVolMix) prints something like 0.3526246 to console). However, using the variable at all in an assignment statement causes it to corrupt whatever is trying to use it to NaN. Example:
console.log(avgVolMix); <- prints a working decimal
var moveRatio = 10 + avgVolMix * 10;
console.log(moveRatio); <- prints NaN
I seriously have no idea why this is happening. I've tried everything to fix it; I've converted it to a string and then back, rounded it to 2 decimal places, adding 0.0001 to it - nothing works! This is the only way I can get it "working" right now:
var temp = 0.0;
for(i = 0; i <= avgVolMix; i+=0.1)
temp = i;
This assigns a number that is close to avgVolMix to temp. However, as you can see, it's extremely bad programming. I should also note that this isn't just broken with this one variable, every variable that's associated with a library I'm using does this (I'm working on a music visualizer). Does anyone know why this might be happening?
Edit: I'm not actually able to access the code right now to test any of this stuff, and since this is a company project I'm not comfortable opening up a jsfiddle anyway. I was just wondering if anyone's ever experienced something like this. I can tell you that I got the library in question from here: http://gskinner.com/blog/archives/2011/03/music-visualizer-in-html5-js-with-source-code.html
If its showing the variable value as NaN. Then try converting the variable as parseInt(); method. Hope it works. Because I also faced such problem and solved when tried it.
I am using the following code
function xhi(aax)
{
var aby=document.getElementById(aax);
aby.style.bottom=(parseInt(aby.style.bottom)+(screen.height-42)/10)+'px';
if(parseInt(aby.style.bottom)<(screen.height-42))setTimeout('xhi("'+aax+'")',25);
}
When i run this code the function calls itself only two times . second time aby.style.bottom becomes Null.Why?
Check the bottom value. It might be crazy, but if the value is something like 008, 010, etc.
parseInt treats the number as octal. In order to avoid this, use :
parseInt(aby.style.bottom,10)
Why are you using bottom? I believe the best approach is the top attribute.
If everything else fails, jQuery has some nice functions to animate and to grab those style attributes.
I am not sure but try after removing from your code +'px' .