簡體   English   中英

僅當數字少於兩位小數時才添加 .00(toFixed)

[英]Add .00 (toFixed) only if number has less than two decimal places

我需要添加零,以便每個數字至少有兩位小數,但沒有四舍五入。 例如:

5      --> 5.00
5.1    --> 5.10
5.11   --> 5.11 (no change)
5.111  --> 5.111 (no change)
5.1111 -->  5.1111  (no change) 

我的函數缺少用於檢查小於兩位小數的 IF:

function addZeroes( num ) {
   var num = Number(num);
   if ( //idk ) {
      num = num.toFixed(2);
   }
   return num;
}

謝謝!

除了以下兩個之外,還發布了一個替代答案。 (請記住,我不是專家,這僅適用於文本輸入,不適用於解析可能存在浮點問題的顏色等復雜值。)

function addZeroes( value ) {
    //set everything to at least two decimals; removs 3+ zero decimasl, keep non-zero decimals
    var new_value = value*1; //removes trailing zeros
    new_value = new_value+''; //casts it to string

    pos = new_value.indexOf('.');
    if (pos==-1) new_value = new_value + '.00';
    else {
        var integer = new_value.substring(0,pos);
        var decimals = new_value.substring(pos+1);
        while(decimals.length<2) decimals=decimals+'0';
        new_value = integer+'.'+decimals;
    }
    return new_value;
}

[這不是一個重復的問題。 您鏈接的問題假設“知道他們至少有 1 位小數”。 在文本輸入中不能假設小數點,這會出錯。]

干得好:

function addZeroes(num) {
// Convert input string to a number and store as a variable.
    var value = Number(num);      
// Split the input string into two arrays containing integers/decimals
    var res = num.split(".");     
// If there is no decimal point or only one decimal place found.
    if(res.length == 1 || res[1].length < 3) { 
// Set the number to two decimal places
        value = value.toFixed(2);
    }
// Return updated or original number.
return value;
}

// If you require the number as a string simply cast back as so
var num = String(value);

請參閱更新的小提琴進行演示。


編輯:自從我第一次回答這個問題以來,javascript 和我已經取得了進展,這是一個使用 es6 的更新解決方案,但遵循相同的想法:

function addZeroes(num) {
  const dec = num.split('.')[1]
  const len = dec && dec.length > 2 ? dec.length : 2
  return Number(num).toFixed(len)
}

更新的小提琴

也許使用.toLocaleString()

var num = 5.1;    
var numWithZeroes = num.toLocaleString("en",{useGrouping: false,minimumFractionDigits: 2});
console.log(numWithZeroes);

作為功​​能/演示:

 function addZeroes(num) { return num.toLocaleString("en", {useGrouping: false, minimumFractionDigits: 2}) } console.log('before after correct'); console.log('5 ->', addZeroes(5) , ' --> 5.00'); console.log('5.1 ->', addZeroes(5.1) , ' --> 5.10'); console.log('5.11 ->', addZeroes(5.11) , ' --> 5.11 (no change)'); console.log('5.111 ->', addZeroes(5.111) , ' --> 5.111 (no change)'); console.log('5.1111 ->', addZeroes(5.1111) , '--> 5.1111 (no change)'); console.log('-5 ->', addZeroes(-5) , ' --> -5.00');

如果你必須使用.toFixed() ,這里是一個單行:

var num = 5.1;    
var numWithZeroes = num.toFixed(Math.max(((num+'').split(".")[1]||"").length, 2));
console.log(numWithZeroes);

或者,再次作為功能/演示:

 function addZeroes(num) { return num.toFixed(Math.max(((num+'').split(".")[1]||"").length, 2)); } console.log('before after correct'); console.log('5 ->', addZeroes(5) , ' --> 5.00'); console.log('5.1 ->', addZeroes(5.1) , ' --> 5.10'); console.log('5.11 ->', addZeroes(5.11) , ' --> 5.11 (no change)'); console.log('5.111 ->', addZeroes(5.111) , ' --> 5.111 (no change)'); console.log('5.1111 ->', addZeroes(5.1111) , '--> 5.1111 (no change)'); console.log('-5 ->', addZeroes(-5) , ' --> -5.00');

下面的代碼提供了一種方法來做你想做的事。 還有其他人。

function addZeroes(num) {
    // Cast as number
    var num = Number(num);
    // If not a number, return 0
    if (isNaN(num)) {
        return 0;
    }
    // If there is no decimal, or the decimal is less than 2 digits, toFixed
    if (String(num).split(".").length < 2 || String(num).split(".")[1].length<=2 ){
        num = num.toFixed(2);
    }
    // Return the number
    return num;
}

console.log(addZeroes(5)); // Alerts 5.00
console.log(addZeroes(5.1)); // Alerts 5.10
console.log(addZeroes(5.11)); // Alerts 5.11
console.log(addZeroes(5.111)); // Alerts 5.111

http://jsfiddle.net/nzK4n/

\n
\n
\n
decimalNumber = number => Number.isInteger(number) ? number.toFixed(2) : number
\n
\n
\n

這是一個可以執行此操作的函數,函數需要一個數字

var addZeroes = function(num) {
  var numberAsString = num.toString();

  if(numberAsString.indexOf('.') === -1) {
    num = num.toFixed(2);
    numberAsString = num.toString();
  } else if (numberAsString.split(".")[1].length < 3) {
    num = num.toFixed(2);
    numberAsString = num.toString();
  }

  return numberAsString
};

對於數字類型文本框

如果數字存在,則附加 .00

 function addZeroes(ev) { debugger; // Convert input string to a number and store as a variable. var value = Number(ev.value); // Split the input string into two arrays containing integers/decimals var res = ev.value.split("."); // If there is no decimal point or only one decimal place found. if (res.length == 1 || res[1].length < 3) { // Set the number to two decimal places value = value.toFixed(2); } // Return updated or original number. if (ev.value != "") { ev.value = String(value); } }
 <input type="number" step=".01" onchange="addZeroes(this)" />

值得一提的是,這是我對此的遞歸解決方案:

const addZeros = (decimal, value, check = true) => {
  if (check && decimal <= value.length) return value;
  if (decimal <= 0) return value;
  const newValue = value.length <= decimal ? '0' + value : value;
  return addZeros(decimal - 1, newValue, false);
};
  • decimal是你想要的小數位數
  • value是你想要的值
  • 不應該設置check ,這是為了防止在第一次調用中出現一些問題。

例如:

  • addZeros(3, "3") ==> "003"
  • addZeros(3, "30") ==> "030"
  • addZeros(3, "300") ==> "300"
  • addZeros(3, "3000") ==> "3000"

我們可以使用有角度的管道來解決這個問題。 我們將把數字信息參數傳遞給十進制管道,看看它是如何工作的——

數字信息參數(3.2-5):

{{ decimal_value | number:'3.2-5' }}

在上面的代碼中,我們指示小數管道在小數點前顯示至少 3 個整數值,最小 2 個小數位,最大 5 個小數位。

if decimal_value = 5.123 then it will print 005.12300
if decimal_value = 53.1 then it will print  053.10

此解決方案檢查數字是否固定

decimalNumber = number => Number.isInteger(number) && number % 1 === 0 ? number : number.toFixed(4);

為我工作 - 讓 a = 12 console.log(a.toLocaleString("en", {u​​seGrouping: false, minimumFractionDigits: 2})) 輸出 - 12.00

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM