[thelist] Just a quick WTF: How to cut off a number after acertainamount of decimals

Matt Warden mwarden at gmail.com
Tue Mar 28 11:51:13 CST 2006


On 3/28/06, Chris at globet.com <Chris at globet.com> wrote:
> I often encounter individuals who, when attempting to solve problems,
> only ever consider solutions that they can implement with their current
> knowledge base.

This might sound snide (not intended), but what else can one do? In
this case, one would have to at least have the knowledge that
exponentiation was a valid operation in the language (or that it was
likely to be a valid operation). This knowledge is required for us to
decide to put forth effort into research.

> With the example given, it may not have been that the
> developer was ignorant of maths in general, but ignorant of the
> existence of the Math object in javascript. Rather than research the
> most suitable technology in more depth in order to provide the most
> appropriate solution, the developer may have chosen to use their time to
> produce an inefficient and tortuous solution because they could do it
> without recourse to research or study.

Well, we should be careful here. Which one of these is the
"inefficient and tortuous solution"?

  function cutVal(val,d){
    var x='100000000000000000000'.substring(0,d+1);
    return parseInt(val*x)/x;
}

function cutOff(val,decimals){
    var x = Math.pow(10,decimals);
    return parseInt(val*x)/x;
}

The first requires that one know that in JavaScript a string like
'100' will be converted implicitly to an integer in the val*x context,
and the second requires that one know that Math.pow(x, y) will return
x^y. I remember when I first saw Math.pow(). I had no idea what it did
(what's a pow?) until I read the documentation.

The 'wtf' comes into play only because more seasoned developers
conform to a solution like the second, using a library function. But
the use of the library function is the only difference in these two
solutions.

So, I guess my point is just that we might want to be careful
distinguishing inefficiency and tortuousness from that which simply
goes against the programmer norm (which one becomes increasingly
accustom to through formal and informal training).

I would consider the most readable solution something like this:

function floorDecimal(decimal, places){
    var shiftfactor = 1;

    // calculate 10^places
    for (var i=1; i<=places; i++) {
        shiftfactor= shiftfactor * 10;
    }

    return parseInt(decimal*shiftfactor)/shiftfactor;
}

The two solutions presented simply offer two ways of getting around
the need for code for the loop in the function (but it's still
there!).

--
Matt Warden
Miami University
Oxford, OH, USA
http://mattwarden.com


This email proudly and graciously contributes to entropy.



More information about the thelist mailing list