Search code examples
javascriptregexti-basic

JS: Replace a number with trailing zeros to scientific notation


I am creating a website that inputs code in TI-BASIC (a built-in, somewhat crappy programming language on the TI-83+/TI-84+ calculators) and attempts to optimize it.

One common optimization is to replace, say, 10000 with 1e4, (more examples: 5500000 to 55e5, .0005 to 5e-3) where 'e' does the same thing as the "*10^(" part of scientific notation. (I hope that is understandable)

This only saves space if there are more than 3 zeros, (numbers are one byte, the 'e' token is 2 bytes) so I do not want to replace the numbers if they have less than 4 zeros.

Because the TI-Calculators only store 14 digits before or after the decimal, I should not need to worry about numbers with more than 14 digits.

I have been using JS RegEx to do a find and replace for all of the other optimizations on the site, so I was experimenting with using that for this problem, but I don't know if there is a better way.

I am not the least experienced with JS RegEx, so any help (even prodding in the right direction) is useful.

Thank you for your time.


Solution

  • You could use Number#toExponential and eliminate the plus sign, if necessary.

    function sansPlus(s) {
        return s.replace('+', '');
    }
    
    console.log(sansPlus(10000..toExponential()));
    console.log(0.00001.toExponential());