3

I am trying to do something I though would be really simple. add the value of 1 to a number.

However the number was plain text and things are getting a little confusing. As you may be able to guess, I am fairly new to this.

My goal is to add 1 point to an existing score, the score has one decimal place, eg 1.3. So the desired result after adding a point is 2.3. However The current script I wrote is returning adds a point to the second decimal place and I don't understand why.

Thanks for the help.

var getPoints = parseInt($('.awesome-points').text(), 10).toFixed(1);
alert(getPoints);
var addPoint = 1;
var newScore = getPoints + addPoint;
$('.awesome-points').text(newScore);

Mark

Mark Hollas
  • 1,107
  • 1
  • 16
  • 44

2 Answers2

9

.toFixed() returns a string (see the MDN documentation), that's why getPoints + addPoint performs string concatenation, not addition.

Call that method after you performed the addition:

// unary + converts any numerical string to a number (no matter whether float
// or int)
var getPoints = +$('.awesome-points').text();
var newScore = getPoints + 1;
$('.awesome-points').text(newScore.toFixed(1));

Or more concise :

$('.awesome-points').text(function(i, val) {
    return (+val + 1).toFixed(1);
});

How this works:

Instead of passing a value to .text(), you can pass a function. This function will be executed for each of the selected elements. The first argument passed to the function is the index of the element in the set of selected elements and the second argument is the current text content. The return value will be set as new text content.
This is a good way to read and write the text content, without invoking .text() twice.

(+val + 1).toFixed(1) is evaluated as follows: First val is converted to a number through the unary plus (+val) and then increased by one (+ 1). .toFixed(1) is called on the result of that operation.

+val will return NaN if the text cannot successfully be converted into a number. I assume this won't happen in your case, but this can easily be dealt with with the expression

return ((+val || 0) + 1).toFixed(1); 

That means, in case +val evaluates to false (which includes NaN), we use 0 instead. It's a common pattern in JavaScript, see also What does "options = options || {}" mean in Javascript?.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Uh, the question wasn't very clear so I just had to re-read it another 3 times after your answer lol. I still don't know exactly what OP wants, but seeing as he probably wants something different than the string which is being returned I'll + your answer. :P – Fabrício Matté May 12 '12 at 00:03
  • I just don't think that anyone wants to perform string concatenation with a *score* ;) But I agree, the question is not very well formulated. – Felix Kling May 12 '12 at 00:06
  • Eeeeh good logic :) Even though you never know what kind of games people are making nowadays. :P – Fabrício Matté May 12 '12 at 00:06
  • Didn't know .toFixed returned a string. Troubling, but worth an upvote ;) – Sampson May 12 '12 at 00:09
  • even best if you add protection to non-numbers turning them to `0`, example `+x||0` – ajax333221 May 12 '12 at 01:14
  • @JonathanSampson - why is it troubling? toFixed does formatting - represent this value rounded to a given number of decimal places. How can a numeric value be formatted other than by turning it into a string? – Mark Reed May 12 '12 at 01:37
  • I didn't know that the unary plus even existed! – SoWeLie May 12 '12 at 01:40
  • @MarkReed It's troubling because you think you're handling a float, when you're really handling a string parading as a float. – Sampson May 12 '12 at 02:31
  • Why would you think it was a float? Floats don't have decimal places; they're just values. You have to have a string representation before you can talk about decimal places. – Mark Reed May 12 '12 at 02:34
  • Thanks. Sorry for the ambiguity in the question. Re-reading it myself I see that I do not actually mention what the desired result is. Thanks for seeing through the fog. – Mark Hollas May 12 '12 at 03:25
  • @FelixKling This might be asking a lot but could you explain just how your more concise example works? Thanks – Mark Hollas May 12 '12 at 06:09
  • @MarkReed I think we're not communicating clearly. `var foo = 3.14;` results in a `number` type, yet it has a decimal. `foo.toFixed(1)`, in my opinion, should result in a rounded single decimal number, `3.1`. It instead results in a string. Granted, it's an easy fix to pop a `+` onto the beginning and output a number, but it doesn't follow what I think the expected outcome should be, IMHO. – Sampson May 12 '12 at 16:12
  • In `var foo=3.14`, the only decimal is in the source code representation of the literal string `3.14` that the interpreter parses to create the numeric value. After the assignment, you won't find a decimal point anywhere in the value of foo - until you turn it back into a string. If the method were called `round` instead of `toFixed`, I might share your expectation, but there is no way to enforce a fixed number of decimals in a floating point value. Even 3.1 is not exactly representable in a float, though the difference is so small that it disappears under most output strategies. – Mark Reed May 12 '12 at 16:58
  • @MarkHollas: You can (and should) edit your question and make it more clear, also for future readers. That said, I updated my question to provide more information about the last part. Hope that helps! – Felix Kling May 13 '12 at 10:09
  • @FelixKling. Thank you for the detailed explanation this is learning gold for a newbie – Mark Hollas May 14 '12 at 16:14
0

i think what you want is something like this

var getPoints = $('.awesome-points').text();
//alert(getPoints);
var addPoint = 1;
var newScore = parseFloat(getPoints) + addPoint;
$('.awesome-points').text(newScore.toFixed(1));

seems that was your answer, toFixed() turns a numerical value into a string so by making the toFixed function later in your process

Ricardo Garza V.
  • 899
  • 1
  • 11
  • 26