Jonny P
Jonny P

Reputation: 453

How can i use Javascript to remove extra decimal places?

I have javascript that finds numbers on a page and multiples them by 10, it only changes numbers inside a class called change number eg:

<b class="multiplyit">0.69</b>

I use the following javascript to acheive this:

var multiplyBy = 10 ;
var elements = document.getElementsByClassName('multiplyit');
for (var i = 0; i < elements.length; i++) {
  elements[i].innerHTML *= multiplyBy;
}

However sometimes this gives me numbers with a lot of decimal points eg. 23.32324334345343434 I would like to restrict these numbers, i have tried using

num.toFixed(2);

However i can seem to get it work work correctly eg:

var multiplyBy = 10 ;
var elements = document.getElementsByClassName('multiplyit');
for (var i = 0; i < elements.length; i++) {
  elements[i].innerHTML *= multiplyBy;
num.toFixed(2);
}

I know i have not added numtofixed properly, i am guessing i need to add it to a variable but i can not figure out which one (new to javascript) How can i acheive this?

Upvotes: 1

Views: 229

Answers (3)

Ilijanovic
Ilijanovic

Reputation: 14904

How about that

  elements[i].innerHTML = (elements[i].innerHTML * multiplyBy).toFixed(2);

No need to declare an extra variable

Upvotes: 2

Barmar
Barmar

Reputation: 780782

You need to use the return value of toFixed().

num = parseFloat(elements[i].innerHTML);
num *= multiplyBy;
elements[i].innerHTML = num.toFixed(2);

Upvotes: 4

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

You can do so in the following manner:

var multiplyBy = 10;
var elements = document.querySelectorAll('.multiplyit');
for (var i = 0; i < elements.length; i++) {
  let num = parseFloat(elements[i].innerHTML)
  num *= multiplyBy
  elements[i].innerHTML = num.toFixed(2)
}
<b class="multiplyit">0.69</b>
<b class="multiplyit">22.42</b>

Upvotes: 2

Related Questions