简体   繁体   中英

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!

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) 

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

Here you are:

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

Hope this help.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM