Posts

Showing posts with the label Math

[Q&D] Fix Decimal Module Operator

This is a Q&D solution for some JavaScript precision problem when we use the module operator with floating point numbers. The Problem If we are dealing with the module operator we could have this case: alert( 8.25 % .05 ); // 0.049999999999999545 We expected 0 but we have a floating point inconsistency instead. This is a well known problem, and not only with JavaScript, truly annoying when we have to show run-time computed money/trends operations. The Solution This comes from my reply in a JS forum, knowing that the module will be a simply floating point, let's say .1 to .001, if we remove floating point from the right side of the operation everything works just fine: function mod(num, mod){ // Another WebReflection silly idea var pow = Math.pow(10, (("" + mod).split(".")[1] || "").length); return ((num * pow) % (mod * pow)) / pow; }; alert( mod(8.25, .05) ); // 0 alert( mod(8.25, .1) ); // 0.5 That's it, have a nice ...

Two simple tricks in JavaScript ( olds, but always useful )

This is a quick post about two really common pieces of code that are used daily from libraries developers and not. Stop to use Math.floor The first one is about usage of Math.floor. It is probably only my opinion, but it seems that Math.floor is used always to perform the same task: var centerWidth = Math.floor((something + someelse - someother) / 2); The point is that at the end of a Math.floor, you will often find that division by 2 . There is a truly simple way to write less, and to obtain best performances as well, it is the right side bitwise operator, that for this purpose is nearly perfect. var centerWidth = (something + someelse - someother) >> 1; That's it! If you compare above examples you will note that second one is about 2X faster than Math.floor. for(var i = 0, t1 = new Date; i Math.floor(i / 2); t1 = new Date - t1; for(var i = 0, t2 = new Date; i i >> 1; t2 = new Date - t2; alert([t1, t2].join("\n")); A tricky String.indexOf Another common pie...