Tom Rudge
Tom Rudge

Reputation: 3272

Trim number before decimal point

<li class="strong font-xs-12 font-sm-14 font-lg-16 red numTxt">£123.99</li>

I just want the value £123 to show, need correct Javascipt to "trim" the number and not round it down or up. I've seen a few ways on here but none that target .class name, in my case .numTxt

If somebody can do me a quick fiddle I would be most appreciative!

Upvotes: 0

Views: 192

Answers (4)

Just use this Regex /\.\d+/:

$.fn.trimDecimal = function(){
  
  $(this).text(function(a, text){
     return text.replace(/\.\d+/,"")
  })
  
}

$(".numTxt").trimDecimal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="strong font-xs-12 font-sm-14 font-lg-16 red numTxt">£123.99</li>
<li class="strong font-xs-12 font-sm-14 font-lg-16 red numTxt">£83.45</li>

To truncate a decimal number, you can do it in this way:

var num = "123.99";
num = +num | 0;

console.log(num)

Upvotes: 2

Ben
Ben

Reputation: 9001

You can do this easily with split()

var str = "£123.99"
var res = str.split(".");

//res is now an array consisting of "£123" and "99"

Working Example:

$('button').click(function(){
    var str = $('#inp').val();
    var res = str.split(".");
   
    $('#output').html(res[0]);
});
input, button, div { display:block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inp" value="£123.99" />
<button>Split At Decimal</button>
<div id="output"></div>

Upvotes: 2

hungndv
hungndv

Reputation: 2141

Here you are:

alert(document.querySelector('li').innerText.replace(/\.\d*/,''));

Hope this help.

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82231

You can use .text() call back function to modify the old text with new text:

$('li.numTxt').text(function(i,val){
    return  val.split(".")[0];
});

Working Demo

Upvotes: 2

Related Questions