number.toString(base) sometimes ignores argument

Posted on
  • Can anyone explain what's going on here?

    scancolor=0

    var temp=255
    =255
    print(temp.toString(16));
    FF
    =undefined
    var temp=255*Math.pow(256,scancolor);
    =255
    print(temp.toString(16));
    255
    =undefined

    Why is the argument to toString() being ignored in the second case?
    Other JS interpreters don't seem to have this behavior.

  • I've just created a bug for this: https://github.com/espruino/Espruino/iss­ues/232

    It's more obvious if you do this:

    >a=255;a.toString(16)
    ="FF"
    >a=255.0;a.toString(16) 
    ="255"
    

    The issue is that floats and integers are treated slightly differently in Espruino. Floats are only output in decimal (at the moment), whereas integers can be output in whatever base is requested.

    So if you want to work around it, for now I'd suggest doing parseInt(a).toString(16)

  • I don't know about Espruino, but in every JS interpreter I've come accross, parseInt is extremely slow. @Gordon could you confirm that Number(a.toFixed(0)).toString(16) is magnitudes faster than parseInt(a).toString(16)? I cannot test yet, since I am still waiting for my boards :)

  • First off, while toFixed is now implemented, you can't cast to a number using Number(...) yet I'm afraid.

    And no... Number(a.toFixed(0)).toString(16) is actually slower than parseInt(a).toString(16) on Espruino, because it'd involve the extra step of creating a number object.

    To be honest if you wanted to be faster, you'd do (a|0).toString(16)

    But it's a bit pointless now, because I just fixed the original bug. It'll be in 1v51 :)

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

number.toString(base) sometimes ignores argument

Posted by Avatar for DrAzzy @DrAzzy

Actions