2

Before this, i want to say sorry. But this is not duplicate. Any answer on other posting has same problem. No float or int in JS (only number). When you make isInt() function, 2.00 always detected true as integer. I want 2.00 detected as float. So, i have to stringify it first.

function isInt(i) {
    if ( i.toFixed ) {
        if ( i % 1 === 0 ) {
            return true; // the problem is 2.00 always detected true as integer. 
            // i want 2.00 detected as float
        } else {
            return false;
        }
    } else {
        return false;
    }
}

then i think i will stringify the 2.00 and then split it with split('.') . But toString doesn't do it

var i = 2.00;
alert(i.toString()); 
// Why this always result 2 . i want the character behind point

So, how to do that? i want 2.00 result "2.00" , not only "2"

Thank you for answering

Slamet Bedjo
  • 103
  • 5
  • 3
    possible duplicate of [How can I check if a string is a float?](http://stackoverflow.com/questions/12467542/how-can-i-check-if-a-string-is-a-float) – Mangiucugna Aug 08 '13 at 12:45
  • 3
    `2.00 === 2; // true`, if you want 2.d.p. see answers, if you want the number of decimal places that you typed in the literal, _JavaScript_ doesn't care and will drop zeros – Paul S. Aug 08 '13 at 12:46
  • Numerically, 2.00 == 2. How is JS supposed to know you want what looks to it like useless 0s, without you explicitly telling it? – cHao Aug 08 '13 at 12:46
  • @Mangiucugna Sorry, this is not duplicate, – Slamet Bedjo Aug 08 '13 at 12:49
  • 1
    Only one type of number exists in javascript: IEEE 754 double precision floating-point. @NULL has the correct answer. –  Aug 08 '13 at 12:54
  • i knew only number. but when you create isInt function, 2.00 will always detected as int, not float. how to solve this? – Slamet Bedjo Aug 08 '13 at 13:03
  • 1
    @SlametBedjo: Simplist answer: you can't within the confines of javascript. There is **no way** to discriminate `2` from `2.0` `2.00` or even `2.0000000000000`. – Brad Christie Aug 08 '13 at 13:12
  • @SlametBedjo Maybe if you treat your number as a string `var i = "2.00"` you could detect the comma and therefore detect if it's a float. – Andreas Louv Aug 08 '13 at 13:14
  • @SlametBedjo ... But you will lose all the functionality with numbers, eq: `"2.00" + "3.00" === "2.003.00"` – Andreas Louv Aug 08 '13 at 13:15
  • @SlametBedjo Acutally, as Llepwryd pointed out, JavaScript has floats only. I really don't see why you are even trying to implement an `isInt` for such a case as it makes no sense. NULL has the perfect answer for the string conversion problem. `isInt` however strongly suggests that your question is in fact a duplicate of the above mentioned question. Could you please tell why treating `2` and `2.00` (the very same values) differently is so important? – Powerslave Aug 08 '13 at 13:15

5 Answers5

7

You can use Number.toFixed(n);

var i = 2;

alert( i.toFixed(2) ); // "2.00"

var i = 1.2345;

alert( i.toFixed(2) ); // "1.23"

Also note that 2 === 2.00 but 2 !== "2.00".

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
  • `.toFixed(2)` cast the number `i` to a string telling that you want two decimal points – Andreas Louv Aug 08 '13 at 12:46
  • @SlametBedjo .toFixed(2) will return a string. http://www.w3schools.com/jsref/jsref_tofixed.asp – Rob Aug 08 '13 at 12:47
  • Thank you :) . yes, only number. But.. the case is, we want to detect 2.00 as float, not as integer. we create function isInt, but, 2.00 true as int, not float – Slamet Bedjo Aug 08 '13 at 12:58
  • @SlametBedjo Please go and read about JavaScript(http://www.w3schools.com/js/js_datatypes.asp), as others have mentioned, there are no ints or floats in javascript. Only Numbers. To detect if a Number has decimal places, check here: http://stackoverflow.com/questions/3885817/how-to-check-if-a-number-is-float-or-integer – Rob Aug 08 '13 at 12:59
  • @SlametBedjo That's not how JavaScript works cause a number covers both integers and floats and all remaining zeros will be removed from a number `0.01 == 0.010 == 0.01000000000`. You connot detect how the number was initialized eg `var i = 2.00`. – Andreas Louv Aug 08 '13 at 13:00
  • @Rob You should consider checking out Mozilla Developer Network (mdn) - also a good reference and maintained by the users (wiki) – Andreas Louv Aug 08 '13 at 13:02
  • @NULL I do, link provided as just to show the different data-types to OP. – Rob Aug 08 '13 at 13:05
2

Answer to revision:

Within javascript there is absolutely no way to distinguish between 2 2.0 and 2.000. Therefore, you will never without some additional decimal place supplied, be able to detect from var a = 2.00 that 2 was ever anything other than an integer (per your method) after it's been assigned.

Case in point, despite the [misleading] built-in methods:

typeof parseInt('2.00', 10) == typeof parseFloat('2.00')
                   'number' == 'number'
                        /* true */

Original Answer:

JavaScript doesn't have hard-based scalar types, just simply a Number. For that reason, and because you really only have 1 significant figure, JavaScript is taking your 2.00 and making it an "integer" [used loosly] (therefore no decimal places are present). To JavaScript: 2 = 2.0 = 2.00 = 2.00000).

Case in point, if I gave you the number 12.000000000000 and asked you to remember it and give it to someone a week from now, would you spend the time remember how many zeros there were, or focus on the fact that I handed you the number 12? (twelve takes a lot less effort to remember than twelve with as many decimal places)

As far as int vs float/double/real, you're really only describing the type of number from your perspective and not JavaScript's. Think of calling a number in JavaScript an int as giving it a label and not a definition. to outline:

Value:     To JavaScript:    To Us:
------     --------------    ------
1          Number            integer
1.00       Number            decimal
1.23       Number            decimal

No matter what we may classify it as, JavaScript still only sees it as a Number.

If you need to keep decimal places, Number.toFixed(n) is going to be your best bet.

For example:

// only 1 sig-fig
var a = 2.00;
console.log(''+a);             // 2
console.log(a.toFixed(2));     // 2.00

// 3 sig-figs
var b = 2.01
console.log(''+b);            // 2.01
console.log(b.toFixed(2));    // 2.01

BTW, prefixing the var with ''+ is the same as calling a .toString(), it's just cast just shorthand. The same outcome would result if I had used a.toString() or b.toString()

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • Javascript only has one numerical data-type, that is Number. toFixed only converts it to a string with the desired number of decimal places. – Rob Aug 08 '13 at 12:53
  • I wasn't implying it had `float` v `decimal` vs `real` vs `int`; Just that there is no hard-set data types. also, you're correct: it results in a string with a force-fixed number of decimal places. – Brad Christie Aug 08 '13 at 12:55
  • Thank you for answering. The case is 2.00 should be detected as float. When every posting create isInt() , 2.00 always `true` as integer, not float – Slamet Bedjo Aug 08 '13 at 12:55
  • @SlametBedjo: As Rob mentioned, there is no `int` in javascript, just simply a `Number` (`int` is more a determination than a scalar type). And JavaScript only stores what it needs to (and since the two supplied decimal places mean nothing in terms of stating the number `2`, it discards them). – Brad Christie Aug 08 '13 at 12:56
  • @BradChristie my mistake, I misunderstood what you meant by "hard-based". Javascript's variables are indeed dynamic and not strongly typed. – Rob Aug 08 '13 at 12:58
  • i know just there is NUMBER. but, we want to create function isInt() . and 2.00 always true as int. not float – Slamet Bedjo Aug 08 '13 at 13:00
  • @SlametBedjo: Well, since JS doesnt have an `int` or a `float` you have to work with how `Number` works (and formats when necessary). – Brad Christie Aug 08 '13 at 13:06
0

To stringify (Chrome at least does so) use this:

i.toPrecision(3)

This will show 2 decimal digits.

Also NULL's solution does it very well without having to calculate the exact precision. i.e. .toFixed(decimals) is your best friend

Powerslave
  • 1,408
  • 15
  • 16
0

You can't do exactly what you want to do.

2.00 gets converted to the number 2 in JavaScript, without decimal points. You can add it back in if you want using .toFixed(2), shown above.

Joe Simmons
  • 1,828
  • 2
  • 12
  • 9
  • because JS only know them as number, The case is, how to detect 2.00 as float, not as int (when you create isInt() function) – Slamet Bedjo Aug 08 '13 at 12:56
0

I suggest keeping "2.00" as a string, as well as parsing it as a number, if necessary, for arithmetic. That way you can distinguish whether the number 2 was entered as "2", or "2.00", or "2.000000". Output the string, not the number, if you want to preserve the original number of decimal places.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75