Question

SO :)

I have some numbers. I want to round them depending on numbers after . sign. The problem is I don't know how much zeros will be after ..

I know functions toPrecision() and toFixed() but they must pass parameter. So I have to know how much signs I need to get after decimal point, but I don't know it.

What I want to achieve?

+++++++++++++++++++++++++++++++++++
+ before            + after       +
+++++++++++++++++++++++++++++++++++
+ 0.0072512423324   + 0.0073      +
+ 0.032523          + 0.033       +
+ 0.000083423342    + 0.000083    +
+ 15.00042323       + 15.00042    +
+ 1.0342345         + 1.034       +
+++++++++++++++++++++++++++++++++++

How I can achieve this?

Was it helpful?

Solution

Try using this:

function roundAfterZeros(number,places){
    var matches=number.toString().match(/\.0*/);
    if(!matches)return number.toString();
    return number.toFixed(matches[0].length-1+places);
}

Here's an explanation

var matches = number.toString().match(/\.0*/) checks for zeros (0) after the point (.).

if(!matches)return number.toFixed(places); if there is no point (.), it must be a whole number, so we just return it (as a string for consistency).

return number.toFixed(matches[0].length-1+places); if it is a decimal, we will round it off to the nearest digits after the zeros (0).

Then run it like roundAfterZeros(0.000083423342,2):

0.000083423342 to "0.000083"
1.0342345 to      "1.034"
1 to              "1"
0.5 to            "0.50"
-300 to           "-300"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top