Oki Erie Rinaldi
Oki Erie Rinaldi

Reputation: 1863

How to recognize that integer value is thousands, hundreds, or tens?

I have several numbers to proceed, let's assume that my numbers are :
14000,32100,510,2100, and 10000
So, how to make the numbers recognized as thousands or hundreds in javascript?
Is there any function for this?

Upvotes: 4

Views: 11790

Answers (6)

Maksym Karunos
Maksym Karunos

Reputation: 51

int x = Math.floor(Math.log10(number)) + 1;

returns the total number of digits of a number (for 100 returns 3, for 1000 returns 4)

Upvotes: 5

Azeem Chauhan
Azeem Chauhan

Reputation: 467

In JavaScript, No method exist to identify a number is hundreds or thousands, but you can create your own ex:

function check(num){
         if(num>999) { return 'thousands'; }
         if(num>99) {  return 'hundreds'; }
}

Upvotes: 0

Alderven
Alderven

Reputation: 8270

Try this one:

var number = 5300;

function NumberName(number)
{
    switch (number.toString().length)
    {
    case 3:
         return "hundreds";
    case 4:
        return "thousands";
    }
}

Upvotes: 7

jongo45
jongo45

Reputation: 3090

Use a logarithm. A base 10 log if available, or make a base 10 log from a natural log (ln) via ln(n)/ln(10). Like so:

var log10=function(n){return Math.log(n)/Math.log(10);};
log10(100);    //2
log10(10000);  //4
log10(1000000);//6, uh actually 5.999999999999999

Might need to round the result due to lack of precision. Rounded version:

function log10(n){
  return Math.round(100*Math.log(n)/Math.log(10))/100;
}
[10,100,1000,10000,100000,1000000].map(log10);

/*
1,2,3,4,5,6
*/

Also you should cache the Math.log(10) result if performance is an issue;

Upvotes: 9

Amit Singh
Amit Singh

Reputation: 2275

I don't know how your Mark-up looks like :

But for a given markup like below:

<div class="save-sale" style="font-size: .8em; padding-top: 4em">10000</div>

You can use something like:

$(function () {
$(".save-sale").click(function (i) {
   var a = $.trim($(".save-sale").text()).length;
    alert(a);
});
});

FIDDLE

Upvotes: 1

patsimm
patsimm

Reputation: 506

I don't know if there is a built-in function like that sorry, but if you just have integers you can write your own function for that:

function numberDigits(number) {
    return number.toString().length
}

Now you can easily dicide if the number is thousands or hundreds etc...

Note that this only works with integer values!

Upvotes: 1

Related Questions