Hate Names
Hate Names

Reputation: 1606

Math.flooring a scientific notation at a certain decimal

I am trying to Math.floor a scientific notation, but at one point the number gets too big and my current method doesn't work anymore. This is what I am using atm

var nr = (number+"").length - 4;
if( nr > 1 ) {
    nr = Math.pow( 10, nr );
    number= Math.floor(number/nr)*nr;
    number= number.toExponential(3);
}

When it becomes a scientific notation by default, I think that's e20+, than my .length method doesn't work anymore since the length it returns isn't accurate. I can think of a work around, and that's to find out the number after e, and update my nr to Math.floor it properly, but it seems like so much work to do something so simple. Here's an example number 8.420960987929105e+79 I want to turn this into 8.420e+79, is there a way I can Math.floor the third decimal point always, no matter what the number is? As it stands when I use toExponential(3) it always rounds the number. My numbers can get as high as e+200 easily, so I need an easier way of doing what I'm currently doing.

Edit: managed to find a work around that works besides Connor Peet's answer for anyone who wants extra options

var nr = 8.420960987929105e+79+"";
var nr1 = nr.substr(0,4);
var nr2 = nr.substr(4, nr.length);
var finalNr = Number(nr1 + 0 + nr2).toExponential(3);

This way is more of a hack, it adds a 0 after the 4th number so when toExponential rounds it up, it gets 'floored' pretty much.

Upvotes: 0

Views: 142

Answers (1)

Connor Peet
Connor Peet

Reputation: 6265

I wrote a little snippet to round a number to a certain number of significant figures some time ago. You might find it useful

function sigFigs(num, figures) {
    var delta = Math.pow(10, Math.ceil(Math.log(num) / Math.log(10)) - figures);

    return Math.round(num / delta) * delta;
}

sigFigs(number, 3); // => 8.420e+79

Upvotes: 1

Related Questions