praveen
praveen

Reputation: 351

How to get first 2 non zero digits after decimal in javascript

I need to get the first 2 non zero digits from a decimal number. How can this be achieved?

Suppose I have number like 0.000235 then I need 0.00023, if the number is 0.000000025666 then my function should return 0.000000025.

Can any one have an idea of how this can be achieved in javascript?

The result should be a float number not a string.

Upvotes: 5

Views: 5876

Answers (4)

Nileksh Dhimer
Nileksh Dhimer

Reputation: 119

Please try the below code:

function keepNonZeroDecimalPlaces(number, minDecimalPlaces) {
    const numStr = number.toString();
    let result = '';
    let decimalCount = 0;

    for (let i = 0; i < numStr.length; i++) {
        const char = numStr.charAt(i);
        if (char === '.') {
            result += char; // Keep the decimal point
        } else if (char !== '0' || decimalCount > 0) {
            result += char;
            if (char !== '0') {
                decimalCount++;
            }
            if (decimalCount >= minDecimalPlaces) {
                break;
            }
        }
    }

    return parseFloat(result);
}

// Example usage
const number1 = 0.00003135110744878017;
const result1 = keepNonZeroDecimalPlaces(number1, 3);
console.log(result1); // Output: 0.00000313

const number2 = 0.000010255258583418511;
const result2 = keepNonZeroDecimalPlaces(number2, 4);
console.log(result2); // Output: 0.00000103

Upvotes: -1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

Here are two faster solutions (see jsperf) :

Solution 1 :

var n = 0.00000020666;
var r = n.toFixed(1-Math.floor(Math.log(n)/Math.log(10)));

Note that this one doesn't round to the smallest value but to the nearest : 0.0256 gives 0.026, not 0.025. If you really want to round to the smallest, use this one :

Solution 2 :

var r = n.toFixed(20).match(/^-?\d*\.?0*\d{0,2}/)[0];

It works with negative numbers too.

Upvotes: 14

adeneo
adeneo

Reputation: 318182

With numbers that has that many decimals, you'd have to return a string, as any parsing as number would return scientific notation, as in 0.000000025666 would be 2.5666e-8

function round(n, what) {
    var i = 0;
    if (n < 1) {
        while(n < 1) {
            n = n*10;
            i++;
        }
    }
    return '0.' + (new Array(i)).join('0') + n.toFixed(what).replace('.','').slice(0,-1);
}

FIDDLE

Upvotes: 2

Piotr Karasiński
Piotr Karasiński

Reputation: 409

var myNum = 0.000256
var i = 1
while(myNum < 10){
    myNum *= 10
    i *= 10
}
var result = parseInt(myNum) / i

Upvotes: 3

Related Questions