Adding decimal to a number multiplies it by ten in Javascript - javascript

I'm having a problem with adding numbers in javascript. I have a variable that keeps track of full number (currentfloatx) and a variable that keeps track of the floored version of that number (newintx). I'm trying to add .25 to currentfloatx, but for some reason its multiplying the number by 10. Does anyone know why it's doing this? Is there something about how javascript is handling these number that I'm missing? Thanks.
//currentfloatx is currently set to 6
alert(currentfloatx + .25); //returns 60.25
alert(currentfloatx); //returns 6
newintx = Math.floor(currentfloatx + .25);
alert(newintx); //returns 60.25

The only way I can think of that would make this happen is if currfloatx holds a string (eg., "6"). This would make currfloatx + .25 be the equivalent of "6" + "0.25", or "60.25".

Related

Logic for my land size calculator application

I'm making this acres and karats calculator for my uncle to help him in his work.
I'll explain the whole idea of this thing with this example. So if you add 3.22 + 2.2 it should be = 5.42 but in this calculator 3.22 + 2.2 should = 6, because 3 acres + 2 acres = 5 acres and 22 karats + 2 karats = 1 acre, so the total would be 6 acres.
The way I'm doing it in the code is that I'm splitting a number like 3.22 to two, 3 and 22 and the other number to 2 and 2 and I add the whole numbers together and the fractions together and if the fractions are >= 24 I add one to the whole numbers and if there're fractions left from the whole calculation I leave it. For example 3.15 + 2.15 = 6.6, but I'm stuck on how I can add the numbers, there's also an error in there that I don't know how to resolve.
Anyway here's the code
function getValue(v) {
return +v.toString().match(/\.(\d*)/)[1] || 0;
}
function getTotal() {
d += Math.floor(num);
p += getValue(num);
if (p >= 24) {
p -= 24;
++d;
}
total = d + p / 100;
ptag.textContent = total;
}
I added the part of the code where I'm stuck.
Note: I'm trying to make the thing able to add multiple numbers not only two. Also I'm trying to add subtraction but I have no idea how to start working on the subtraction because I haven't even finished the addition.
If the error you are talking about is something like this:
Uncaught TypeError: Cannot read property '1' of null
It is because of your getValue function.
My suggestion is, instead of using something as complicated as
function getValue(v) {
return +v.toString().match(/\.(\d*)/)[1] || 0;
}
use
function getValue(v) {
return floor((v % 1) * 100);
}
This has the same effect as the code you wrote. Which for example, from input 3.13, returns 13.
But there are few other problems.
First, you should update your num variable every now and often, otherwise, it is always going to stay as an empty string (you only defined it on line 20, and you didn't update it after that).
Second, you should clear the d and p variable after you use. As of right now, both of these variables just keeps on increasing every time you run the getTotal function
For your question of how you can add two numbers, I suggest you to create a variable where you can store the first number that the user typed.
For example, when the user typed in 4.19 and pressed the plus button, save that 4.19 into a variable (let's say firstNum).
Then when the user pressed equal button, add the number from the current input field with the firstNum variable.
On how exactly you are going to add two different numbers, break two numbers you want to add into Acres part and Karats parts. Then add them separately, then use your getTotal.
So if the number is 3.21 and 5.18, add 3 and 5, add 21 and 18, then add both of them.
you'll get 8.39. Finally, convert 8.39 into 9.15.
Sorry if my calculation is not correct. It is my first time with this concept!
But I believe this is the way to go.

Extra numbers being added when decrementing value from number with JavaScript [duplicate]

This question already has answers here:
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 5 years ago.
I'm trying to decrement "0.01" from a number, it works fine the first time, but when I try to decrement one more time it adds some extra numbers.
Here is my JavaScript code:
function decrement() {
var credits_sidebar = $('#credits_sidebar').html();
var credits_update = credits_sidebar - 0.01;
$("#credits_sidebar").fadeOut('');
$("#credits_sidebar").html(credits_update);
$("#credits_sidebar").fadeIn('');
}
If you click once on the decrement button it works, but if you click another time, the number will be "95.97999999999999" it should be 95.98 instead.
Here's an example JsFiddle:
https://jsfiddle.net/rozvnay1/
var credits_update = (credits_sidebar - 0.01).toFixed(2)
JSFiddle demo: https://jsfiddle.net/8eakhn4L/1/
This is a problem with floating point value representation.
You should consider using
Math.round((credits_sidebar - 0.01)* 100)) / 100
This behavior is normal and expected because of the way floating point math is done in JavaScript.
However what you simply can do is multiply your number by a factor of 100 to make it a whole number that needs to be decremented then you can do the decrement and divide the result by 100 to get the correct decimal answer.
You need to update this for working of code:
var credits_update = (credits_sidebar - 0.01).toFixed(2);

Javascript issue with localstorage (value changing itself) [duplicate]

This question already has answers here:
What is JavaScript's highest integer value that a number can go to without losing precision?
(21 answers)
Large numbers erroneously rounded in JavaScript
(6 answers)
Closed 5 years ago.
i'm currently trying to store data via localstorage on my website, and if for example I do so :
localStorage.setItem("vue",10206726906969851)
When I want to get the value back I get this result :
localStorage.getItem("vue")
-> "10206726906969852"
So why does the value changes ? Thank you in advance for your help
JavaScript is not epic at precision with numbers. An example:
.2 + .2 = .4
but
.2 + .2 + .2 = 0.6000000000000001
The number you are using is too big for JS to maintain good precision on it. Log the following in your console and you will see what I mean.
10206726906969851 > Number.MAX_SAFE_INTEGER // returns true
The number you are using is too big. I have experienced this in the past. The server will give me numbers that are fine for Java, but too large for JavaScript. So... JS will mess them all up. The only way to fix was to get a shorter number that JS wouldn't barf on.

Order of operations for Math.floor(Math.random() * 5 + 1)?

In the Code Academy JS course, Dragon Slayer 2/6, the following text is used in the hint to describe the order of operations for the code I included in the title.
How does this code work?
Math.floor(Math.random() * 5 + 1);
First we use Math.random() to create a random number from 0 up to 1. For example, 0.5
Then we multiply by 5 to make the random number from 0 up to 5. For >example, 0.5 * 5 = 2.5
Next we use Math.floor() to round down to a whole number. For example, >Math.floor( 2.5 ) = 2
Finally we add 1 to change the range from between 0 and 4 to between 1 and >5 (up to and including 5)
I've looked this up in several different places (here and here), and a majority of them either focus on the range that Math.random() produces (which I understand) or confirm the order of operations outlined in the hint, wherein "Math.floor" acts upon "Math.random()*5" prior to the "+1" being added.
It seems to me however that, according to the order of operations that I learned in school, the last two steps should be flipped. Would that not be the case since "Math.random()*5" and the "+ 1" are both within the parenthesis?
While the difference between these two might not make a difference in the value returned from this particular code, I could see a fundamental change in the order of operation like the one outlined here would cause me some frustration further down the road if I didn't know it.
Math.floor() will work on whatever is inside the brackets, after it has been calculated.
Math.floor(Math.random() * 5 + 1)
is the same as
var i = Math.random() * 5;
i += 1;
Math.floor(i);
You are correct that the wording on the page is wrong. The last thing that will happen is the floor call. Everything in the parenthesis will be processed first.
Honestly, I think they mixed up here, and you're right. According to PEMDAS and any mathematics I've ever learned, the +1 comes before the Math.floor function.
The Math.random() function returns a random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive). It can be any thing like 0,.34,.42 etc.
if you want random number between 0-5.
you will used Math.Random()*5. This will give you any number like 0,4.43.4.34 but not five.
Then we add 1 like this Math.random() * 5 + 1. Now the chances is you will get a number which is between 0 and 6. But you don't want number above 5. so
you apply floor method which will return largest integer less than or equal to a given number.

Javascript rounding down

So I've looked into this for several hours before finally giving up and asking help.
I'm currently trying to form fill a character sheet for Pathfinder (D&D 3.5 equivalent) using adobe acrobat. I want to make it so when I fill in my strength score it will auto fill out anything that has to do with strength.
More specifically I need it to take my ability score divide by two and subtract 5 for my ability modifier. But when I use 17 for instance as my Strength score my modifier is 4. I need it to round down not up.
I tried to subtract 5.5 instead and that works until its 10 or lower. At which point I have the opposite problem.
My current code is Strength/2-5
Use Math.floor() like this:
var score = 17.0;
result = Math.floor((score / 2) - 5);
alert(result)
Output:
3
Original:
Strength/2-5
(it worked but it needed to round down instead of up)
Final:
var a = this.getField("Strength")
event.value = Math.floor((a.value - 10) / 2)
Thank you for trying everybody! Process of elimination gets it done

Categories