[英]How to get Last digit of number
如何使用 jquery 提取 Number 值的最后(結束)數字。 因為我必須檢查數字的最后一位數字是 0 還是 5。所以如何獲得小數點后的最后一位數字
對於前。 var test = 2354.55
現在如何使用 jquery 從這個數值中得到 5。 我試過substr但這僅適用於字符串而不適用於數字格式
就像我使用var test = "2354.55";
那么它會起作用,但如果我使用var test = 2354.55
那么它不會。
這對我們有用:
var sampleNumber = 123456789, lastDigit = sampleNumber % 10; console.log('The last digit of ', sampleNumber, ' is ', lastDigit);
適用於小數:
var sampleNumber = 12345678.89, lastDigit = Number.isInteger(sampleNumber) ? sampleNumber % 10 : sampleNumber.toString().slice(-1); console.log('The last digit of ', sampleNumber, ' is ', lastDigit);
單擊運行代碼片段進行驗證。
試試這個:
var test = 2354.55; var lastone = +test.toString().split('').pop(); console.log("lastone-->", lastone, "<--typeof", typeof lastone); // with es6 tagged template and es6 spread let getLastDigit = (str, num)=>{ return num.toString(); }; let test2 = 2354.55; let lastone2 = +[...getLastDigit`${test2}`].pop(); console.log("lastone2-->", lastone2, "<--typeof", typeof lastone2);
ES6/ES2015 更新:
在數字不可迭代的情況下,我們可以使用標記模板。 因此,我們需要將數字轉換為它的字符串表示形式。 然后只需傳播它並彈出最后一個數字。
你可以只轉換為字符串
var toText = test.toString(); //convert to string
var lastChar = toText.slice(-1); //gets last character
var lastDigit = +(lastChar); //convert last character to number
console.log(lastDigit); //5
這是另一個使用.slice()
:
var test = 2354.55; var lastDigit = test.toString().slice(-1); //OR //var lastDigit = (test + '').slice(-1); alert(lastDigit);
有一個 JS 函數.charAt()
您可以使用它來查找最后一位數字
var num = 23.56 var str = num.toString(); var lastDigit = str.charAt(str.length-1); alert(lastDigit);
如果您想要百分位的數字,那么您可以執行以下操作:
test * 100 % 10
轉換為字符串並獲取最后一位數字的問題在於它沒有給出整數的百分位值。
就在一行。
const getLastDigit = num => +(num + '').slice(-1); console.log(getLastDigit(12345)) // Expect 5
toString()
將數字轉換為字符串,而charAt()
為您提供特定位置的字符。
var str = 3232.43; lastnum = str.toString().charAt( str.length - 1 ); alert( lastnum );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.