How to use Y.Number.format and decimalPlaces?

266 views Asked by At

I'm trying use Y.Number.format for formatting my numbers. I need to use 6 decimalPlaces but if there is one and and don't use right zero-padding if the source number has no this count of decimals.

Basically I need the following:

YUI().use("datatype-number", function(Y) {
    console.log(Y.Number.format(1234.567, {
       thousandsSeparator: ".",
       decimalPlaces: 2
    }
));

//Result is: 1234.57

and

YUI().use("datatype-number", function(Y) {
    console.log(Y.Number.format(1234.567, {
       thousandsSeparator: ".",
       decimalPlaces: 6
    }
));

//Result is 1234.567

How could I achieve the results above?

1

There are 1 answers

0
HMR On BEST ANSWER

Maybe this will work (num%1) is num modulo 1. Divide num by 1 and see what's left over.

3%2=1
12%5=2
1.0001%1=0.0001

Example of how you can use it:

;YUI().use("datatype-number", function(Y) {
    var num=1.0000;//no decimal places
    var decPlaces=((num%1)>0.0000005)?6:0;
    console.log(Y.Number.format(num, {
       thousandsSeparator: ".",
       decimalPlaces: decPlaces
    }));
    num=1.0010;//some decimal places
    decPlaces=((num%1)>0.0000005)?6:0;//6 if dec places 0 if not
    console.log(Y.Number.format(num, {
       thousandsSeparator: ".",
       decimalPlaces: decPlaces
    }));
    num=1.0000001;//not enough decimal places
    decPlaces=((num%1)>0.0000005)?6:0;//6 if dec places 0 if not
    console.log(Y.Number.format(num, {
       thousandsSeparator: ".",
       decimalPlaces: decPlaces
    }));    
});