Oli Fletcher
Oli Fletcher

Reputation: 309

Removing a decimal place in the DOM

I have a hunk of HTML, that is generated through PHP, and generates a number with two decimal places, within a span, with the class of "amount":

<span class="amount">200.00</span>

What I am looking to do is use a client side method to alter the text within the span so it does NOT have decimal places (i.e. in this case; 200), so I don't need to edit any of the original PHP, as this is generated through a plugin.

Any thoughts welcome.

Upvotes: 1

Views: 120

Answers (2)

Patrick Evans
Patrick Evans

Reputation: 42736

You can use jQuery's .each method to loop through each element, and then just use the split method to get the integer part

$(function(){
  //Go through each element
  $(".amount").each(function(item){
     //split the text on the dot, and then take the front piece
     $(this).text( $(this).text().split(".")[0] );
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="amount">200.00</span><br />
<span class="amount">220.40</span><br />
<span class="amount">5.40</span><br />
<span class="amount">90.95</span><br />

Note if you know before hand that the values will always have a .00 value you can just use

$(this).text( +$(this).text() );

by forcing it to be a number (by having the + in front) and back to a string (when it gets set as the element text) will cause it to lose the decimal part

Upvotes: 2

Arindam Nayak
Arindam Nayak

Reputation: 7462

You can get value as $("span.amount").text().replace(".",""). In JS it would replace just one instance of ".", you are good enough to use this.

Upvotes: 0

Related Questions