Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Math.floor issue between specific range of numbers

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?

like image 775
ron_meh Avatar asked May 14 '15 01:05

ron_meh


People also ask

Why is Math floor not working?

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.

What is the difference between Math Trunc () and Math floor () in JavaScript?

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.

How do you floor a value in JavaScript?

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.

What does Math floor () do in JavaScript?

The Math.floor() function always rounds down and returns the largest integer less than or equal to a given number.


1 Answers

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.

like image 189
jfriend00 Avatar answered Sep 28 '22 22:09

jfriend00