Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
i am trying to round a numeric value to upto 2 decimal places in javacript.
Please try to access the following url
https://www.jsnippet.net/snippet/1665/1/Rounding-a-value-upto-2-decimal-places
If you notice the code i am trying to round the following values
3.225 , 4.225 and 5.225
If you notice the result, 3.225 is rounded of to 3.23 which is correct.
Also 5.225 is rounded of to 5.23 which is also correct but 4.225 is getting rounded of to 4.22 instead of 4.23
Can anyone please tell me how to fix this.
try this..
Number(Math.round(3.225+'e2')+'e-2');
This is a painful task on Javascript. From my experience, I do things like this:
function round(n, places = 2) {
var epsilon = Number.EPSILON*1000;
var exponent = Math.pow(10, places);
var integral = Math.round((n+epsilon) * exponent);
return integral/exponent;
}
epsilon is a very small number to compensate this behavior of floats in JavaScript.
Note: please don't use this function for sensitive data, is just a very very simple rounding function.
if you have to deal with sensitive data, use MathJS as user King suggested.
Use the mathjs library, provided here. The round function provided by this library is more precise than the builtin library. I've already tested your code using it and it works!
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am wondering how to remove decimals in large numbers without it having to round off?
My float is:
number = 32.223516
The result that I want is 32223516.
When I do this:
parseInt(number * 1000000, 10) it gives me 32223515.
And if I use Math.ceil or Math.round, it'll be a problem for cases that would need it to round down.
Is there a cleaner way to do this?
Advance thanks!
Number.parseInt(
yourVariable.toString().replace('.', '')
);
Try this:
let number = 32.223516
console.log(parseInt(number.toString().replace('.', '')));
If you know that the number always needs to be multiplied by 1000000 to get what should be the whole number version of it, do that with Math.round:
console.log(Math.round(32.223516 * 1000000));
Otherwise, I'd be tempted to take a round trip through a string:
console.log(+(32.223516).toString().replace(".", ""));
...but you need to beware of scientific notation, see the answers here for how to convert the number to string without scientific notation.
That is an example of how JavaScript handles all numbers as floating-point numbers.
What can help you in this case is if you convert the number to string form, retain only the desired amount of numbers after the decimal point, which is probably 0 in your case, by using toFixed() method, which would convert and round-off accordingly, like so:
number = 32.223513;
numberToFixed = (num * 1000000).toFixed(0); //argument is amount of numbers to be retained after decimal point
I'm sure this is simple, but in my javascript code, I have two numbers. One contains a decimal, and the other doesn't, and I add them together (ie. 7.5 + 5), I am getting a result with NO decimal value.
Do I need to cast each number variable as a double? I know that all numbers are doubles in javascript - which is why I do not understand this behavior...
For instance, I have var answer = week1 + week2;. Does this make sense?
Thanks in advance!
I am sorry for wasting time - turns out I was using parseInt instead of parseFloat to gather the "week" values I spoke about.
Can someone please close this question or delete it? Before the shame consumes me?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm currently making a calculator with HTML, CSS and Javascript, for practice. I found out that the "built in" eval function did the math from a string. But it doesn't work properly.
I don't know what the problem is. But when i for example do: 11+11/2 which should be 11. Becomes 16.5 for some reason. I have no idea why. I would really appreciate some help.
Here is the code:
function revealAnswer(){
var math = document.getElementById("numbersInputted");
math.innerHTML += " = " + eval(math.innerHTML);
}
There are a whole bunch of reasons why this is the wrong approach.
First, innerHTML returns a string containing, not only the text content of an element, but also any nested HTML elements as well. If it's just the text you want, use textContent.
Next, by having the user input the actual math operator they want to use in the same string with the numbers creates more confusion. Have the user enter that separately and then you can use if/then logic to ultimately use the correct operator.
Next (and this is the important part), don't ever use eval(). It is not required to solve just about any problem you could encounter, but it opens up the door to "Cross Site Scripting" attacks on your website. Additionally, it manipulates the this binding and executes its code in its own scope.
What you really need to do is simply convert the string input into a number so that you can do math with it. You can do this with parseInt() and parseFloat()
So, your line could be:
math.innerHTML += " = " + parseFloat(math.textContent);
Lastly, for math, the order of operations is:
Parenthesis
Exponents
Multiplication
Division
Addtion
Subtraction
You can see that division is done prior to addition and that means that in your expression: 11 + 11/2, first 11/2 is evaluated (5.5) and then it is added to 11 (16.5).
Finally, remember that the + operator in JavaScript can mean mathematical addition or string concatenation and if one of the operands is a string, the other will be converted to a string.
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 7 years ago.
I am pretty new in JavaScript and I have found a very strange situation doing an extremely simple mathematical operation: a subtraction.
So in a jQuery function I have this code:
saldoRicalcolato = finanziamento - variazioneAnticipoNumber;
Where finanziamento and variazioneAnticipoNumber are 2 numbers having decimal digits.
It works almost always good except for some specific values.
You can replicate the strange behavior performing this statement into the FireBug console:
2205.88 - 1103.01
1102.8700000000001
So in this case the result is substantially wrong because I obtain 1102.8700000000001 and not 1102.87 as I expected.
Why? What am I missing? Is it a JavaScript engine bug or something like this? Possible?
It's not a JavaScript problem but a more general computer problem. Floating number can't store all decimal numbers properly, because they store stuff in binary For example:
0.5 is store as b0.1
but 0.1 = 1/10 so it's 1/16 + (1/10-1/16) = 1/16 + 0.0375
0.0375 = 1/32 + (0.0375-1/32) = 1/32 + 00625 ... etc
so in binary 0.1 is 0.00011...
but that's endless. Except the computer has to stop at some point. So if in our example we stop at 0.00011 we have 0.09375 instead of 0.1.
It doesn't depend on which language but on the computer, what depends on the language is how you display the numbers. Usually the language will round numbers to an acceptable representation but apparently JavaScript doesn't.
If you're looking to get 1102.87. You'll need to set the decimal place to 2 by using toFixed()
This is just a solution of getting the number you want.
alert((2205.88 - 1103.01).toFixed(2));
This question already has answers here:
Generating random whole numbers in JavaScript in a specific range
(39 answers)
Closed 7 years ago.
This post was edited and submitted for review 6 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I need to create a random number between 0.0200 and 0.120 using JavaScript. How would I do this?
I specifically am interested in floating point numbers, not whole numbers. The question linked (Generating random whole numbers in JavaScript in a specific range) specifically asks for "Generating random whole numbers", so even if some of the answers to the linked question specify how to do it for floats, it is not clear that is what they are doing. This question is clearly looking for a random number between floats and so is not a duplicate.
You could use
(Math.random() * (0.120 - 0.0200) + 0.0200).toFixed(4)
toFixed(n) is used to convert a number into a string, keeping only the "n" decimals.
Here you are:
function generateRandomNumber() {
var min = 0.0200,
max = 0.120,
highlightedNumber = Math.random() * (max - min) + min;
alert(highlightedNumber);
};
generateRandomNumber();
I understand your real question — you do not know how to get a random number between floating numbers, right? By the way, the answer is passed before.
To play with the code, just click here to jsFiddle.
Update
To get the four first numbers of your decimal, use .toFixed(3) method. I've performed an example here, on jsFiddle.
If you're looking to generate that and other random numbers or things, I'd suggest taking a look the Chance library. It provides a nice abstraction layer so you don't have to fiddle with Math.random() and write your own.
chance.floating({min: 0.02, max: 0.12});
Full disclosure: I'm the author so I'm a bit biased :)
Also, if this is the only random thing you need to generate or it's client-side where size is a real issue, I'd suggest just using one of the suggestions above. Not worth a few Kb where a couple lines will do.