veryserious
veryserious

Reputation: 305

Remove the period and everything after it using jQuery

Is there a way to remove the period and everything after it using jQuery? The numbers following the period vary in length, so it's not as simple as finding the length.

For example:

<span class="changethis">505.234</span> <span class="changethis">23.93</span>

Thanks for your help!

P.S. (bonus) If there is a way to round up if it's x.5 or higher that would be awesome. Not essential though.

Upvotes: 1

Views: 746

Answers (4)

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41767

This should do the trick (including rounding):

$(function() {
  var element = $('.changethis'); 
  var number =  parseFloat(element.html());
  element.html(number.toFixed(0));
});

Upvotes: 1

Chao
Chao

Reputation: 3043

Assuming that the contents of the spans will only ever be numeric then this will do what you need:

$("SPAN.changethis").each( function(index, elem) {
    $(elem).text(Math.round($(elem).text()))
});

The first selector gets all the spans, then iterate over each span replacing its contents with the result of Math.round() of its contents.

Upvotes: 0

Peter Hanley
Peter Hanley

Reputation: 1284

The Javascript to handle the truncation and rounding is built in to the language, no jQuery needed:

x=Math.round(505.234)

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/round

Upvotes: -1

Xyan Ewing
Xyan Ewing

Reputation: 912

Try this.

$('.changethis').each(function () {
    $(this).html(Math.round(parseFloat($(this).html())));
});

http://jsfiddle.net/d4fv8/1/

Upvotes: 4

Related Questions