Reinier
Reinier

Reputation: 13

Javascript - Format number to always show the original decimal places

I need a js function that show the original count of decimals in a number. For example:

value          display
2.31             2
1.0              1
2.3500           4

The problem is that i dont know how get the count of decimals. I have that code: value=2.3500; return CountofDecimals(value); // must be display 4:

Anything help??? Thanks :P

Upvotes: 1

Views: 226

Answers (4)

starbeamrainbowlabs
starbeamrainbowlabs

Reputation: 6136

You could use this function:

function decimalplaces(number)
{
    numberastring = number.toString(10);
    decimalpoint = numberastring.indexOf(".");

    if(decimalpoint == -1)
    {
       return 0;
    }
    else
    {
        return numberastring.length - decimalpoint - 1;
    }
}

Upvotes: 0

Daniel B. Chapman
Daniel B. Chapman

Reputation: 4687

Caveat: I hate this answer, I don't really advocate it

Don't store it as a number, store it as a string. This can result in "stringly typed" code quickly so it is inadvisable. It is a workaround since JavaScript uses a float as the number type.

Alternatively store it as an Object and parse out the format via a function call:

{ value = "1.2345", decimal = 4} 

and use that to create the correct number format. If I had the requirement this is probably the hack I'd use. Or, I would have my server return the formatted string as you can pull that off easily server side.

Upvotes: 1

simekadam
simekadam

Reputation: 7384

If it would be possible take these numbers as strings, it definitely is possible..And quite simple actually.

function countDecimals(string){
   var delimiters = [",","."];
   for(var i = 0; i<delimiters.length; i++){

        if(string.indexOf(delimiters[i])==-1) continue;
        else{
        return string.substring(string.indexOf(delimiters[i])+1).length;
    }
 }
}

Upvotes: 1

Ry-
Ry-

Reputation: 225203

That's not possible. There's no difference between the number 3.5 and 3.50 in JavaScript, or indeed in any other common programming language.

If you actually mean they're strings (value = '2.3500' rather than value = 2.3500) then you can use indexOf:

var decimalPlaces = value.length - value.indexOf('.') - 1;

Upvotes: 4

Related Questions