I'm facing an issue with Math.floor function of javascript for the below scenario:
1) from the value betwwen 8192 and 10484,
if I type 8192.8 -> The Math.floor converts it into 8192.79
if I type 8192.88 -> The Math.floor converts it into 8192.87
if I type 8192.3 -> The Math.floor converts it into 8192.29
Strange part is that except from the range given above the function works fine.
HTML:
<div data-bind="text: popIncrease"></div>
<input type="text" data-bind="value: userInput, valueUpdate: 'afterkeydown'" />
Javascript:
var ViewModel = function () {
var _self = this;
_self.userInput = ko.observable();
_self.popIncrease = ko.computed(function () {
return parseFloat((Math.floor(_self.userInput() * 100) / 100)).toFixed(2);
});
};
ko.applyBindings(new ViewModel());
jsfiddle:https://jsfiddle.net/91z5bdy4/1/
When I changed 100 with 1000 it solved the error but I do not understand why this happened on the first place?
Math. floor is not working because you changed the value of temperature into a rounded version. You are not meant to alter the temperature variable at all during this task.
trunc rounds down a number to an integer towards 0 while Math. floor rounds down a number to an integer towards -Infinity . As illustrated with the following number line, the direction will be the same for a positive number while for a negative number, the directions will be the opposite.
In JavaScript, floor() is a function that is used to return the largest integer value that is less than or equal to a number. In other words, the floor() function rounds a number down and returns an integer value.
The Math.floor() function always rounds down and returns the largest integer less than or equal to a given number.
You can just switch to this:
return parseFloat(_self.userInput()).toFixed(2);
Working version of your jsFiddle: https://jsfiddle.net/jfriend00/5rLL04Lk/
Or, if you want to work around some of the idiosyncrasies of .toFixed()
, you can use this:
return (Math.round(_self.userInput() * 100) / 100).toFixed(2);
Working jsFiddle: https://jsfiddle.net/jfriend00/xx2aj2L0/
This solution passes all three of your test cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With