簡體   English   中英

將數字截斷到兩位小數而不四舍五入

[英]Truncate number to two decimal places without rounding

假設我的值為 15.7784514,我想將其顯示為 15.77,不進行四舍五入。

var num = parseFloat(15.7784514);
document.write(num.toFixed(1)+"<br />");
document.write(num.toFixed(2)+"<br />");
document.write(num.toFixed(3)+"<br />");
document.write(num.toFixed(10));

結果是 -

15.8
15.78
15.778
15.7784514000 

如何顯示 15.77?

將數字轉換為字符串,將數字匹配到小數點后第二位:

 function calc(theform) { var num = theform.original.value, rounded = theform.rounded var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0] rounded.value = with2Decimals }
 <form onsubmit="return calc(this)"> Original number: <input name="original" type="text" onkeyup="calc(form)" onchange="calc(form)" /> <br />"Rounded" number: <input name="rounded" type="text" placeholder="readonly" readonly> </form>

toString不同, toFixed方法在某些情況下會失敗,所以要非常小心。

2016 年 11 月 5 日更新

新答案,永遠准確

function toFixed(num, fixed) {
    var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?');
    return num.toString().match(re)[0];
}

由於javascript 中的浮點數學總是有邊緣情況,所以以前的解決方案在大多數情況下都是准確的,這還不夠好。 有一些解決方案,例如num.toPrecisionBigDecimal.jsaccounting.js 然而,我相信僅解析字符串將是最簡單且始終准確的。

基於@Gumbo 接受的答案中編寫良好的正則表達式的更新,這個新的 toFixed 函數將始終按預期工作。


舊答案,並不總是准確的。

滾動你自己的 toFixed 函數:

function toFixed(num, fixed) {
    fixed = fixed || 0;
    fixed = Math.pow(10, fixed);
    return Math.floor(num * fixed) / fixed;
}

我選擇寫這個來手動刪除字符串的其余部分,這樣我就不必處理數字帶來的數學問題:

num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf("."))+3); //With 3 exposing the hundredths place
Number(num); //If you need it back as a Number

這將為您提供“15.77”,其中 num = 15.7784514;

另一種單線解決方案:

number = Math.trunc(number*100)/100

我使用 100 是因為您想截斷到第二個數字,但更靈活的解決方案是:

number = Math.trunc(number*Math.pow(10, digits))/Math.pow(10, digits)

其中digits是要保留的小數位數。

有關詳細信息和瀏覽器兼容性,請參閱Math.trunc 規范

更新(2021 年 1 月)

根據其范圍,javascript 中的數字可能會以科學計數法顯示。 例如,如果您在控制台中鍵入 0.0000001,您可能會看到它為 1e-7,而 0.000001 看起來沒有改變 (0.000001)。 如果您的應用程序適用於不涉及科學記數法的一系列數字,您可以忽略此更新並使用下面的原始答案。

此更新是關於添加一個函數來檢查數字是否為科學格式,如果是,則將其轉換為十進制格式。 在這里,我提出了這個,但您可以根據應用程序的需要使用任何其他實現相同目標的功能:

 function toFixed(x) { if (Math.abs(x) < 1.0) { let e = parseInt(x.toString().split('e-')[1]); if (e) { x *= Math.pow(10,e-1); x = '0.' + (new Array(e)).join('0') + x.toString().substring(2); } } else { let e = parseInt(x.toString().split('+')[1]); if (e > 20) { e -= 20; x /= Math.pow(10,e); x += (new Array(e+1)).join('0'); } } return x; }

現在只需將該函數應用於參數(這是相對於原始答案的唯一更改):

 function toFixedTrunc(x, n) { x = toFixed(x) // From here on the code is the same than the original answer const v = (typeof x === 'string' ? x : x.toString()).split('.'); if (n <= 0) return v[0]; let f = v[1] || ''; if (f.length > n) return `${v[0]}.${f.substr(0,n)}`; while (f.length < n) f += '0'; return `${v[0]}.${f}` }

此更新版本還解決了評論中提到的一個案例:

0           => 0.00
0.01        => 0.01
0.5839      => 0.58
0.999       => 0.99
1.01        => 1.01
2           => 2.00
2.551       => 2.55
2.99999     => 2.99
4.27        => 4.27
15.7784514  => 15.77
123.5999    => 123.59

再次,選擇最適合您的應用程序需求的內容。

原始答案(2017 年 10 月)

對於任何 n≥0,將數字截斷(不舍入)到第 n 個十進制數字並將其轉換為具有恰好 n 個十進制數字的字符串的一般解決方案。
 function toFixedTrunc(x, n) { const v = (typeof x === 'string' ? x : x.toString()).split('.'); if (n <= 0) return v[0]; let f = v[1] || ''; if (f.length > n) return `${v[0]}.${f.substr(0,n)}`; while (f.length < n) f += '0'; return `${v[0]}.${f}` }

其中 x 可以是數字(轉換為字符串)或字符串。

以下是 n=2 的一些測試(包括 OP 要求的測試):

 0 => 0.00 0.01 => 0.01 0.5839 => 0.58 0.999 => 0.99 1.01 => 1.01 2 => 2.00 2.551 => 2.55 2.99999 => 2.99 4.27 => 4.27 15.7784514 => 15.77 123.5999 => 123.59

對於 n 的其他一些值:

 15.001097 => 15.0010 (n=4) 0.000003298 => 0.0000032 (n=7) 0.000003298257899 => 0.000003298257 (n=12)

parseInt 比 Math.floor 快

function floorFigure(figure, decimals){
    if (!decimals) decimals = 2;
    var d = Math.pow(10,decimals);
    return (parseInt(figure*d)/d).toFixed(decimals);
};

floorFigure(123.5999)    =>   "123.59"
floorFigure(123.5999, 3) =>   "123.599"
num = 19.66752
f = num.toFixed(3).slice(0,-1)
alert(f)

這將返回 19.66

這不是一個安全的選擇,因為許多其他人評論的例子中的數字變成了指數符號,這個功能沒有涵蓋風景

 // typescript // function formatLimitDecimals(value: number, decimals: number): number { function formatLimitDecimals(value, decimals) { const stringValue = value.toString(); if(stringValue.includes('e')) { // TODO: remove exponential notation throw 'invald number'; } else { const [integerPart, decimalPart] = stringValue.split('.'); if(decimalPart) { return +[integerPart, decimalPart.slice(0, decimals)].join('.') } else { return integerPart; } } } console.log(formatLimitDecimals(4.156, 2)); // 4.15 console.log(formatLimitDecimals(4.156, 8)); // 4.156 console.log(formatLimitDecimals(4.156, 0)); // 4 console.log(formatLimitDecimals(0, 4)); // 0 // not covered console.log(formatLimitDecimals(0.000000199, 2)); // 0.00

這樣做很簡單

number = parseInt(number * 100)/100;

只需截斷數字:

function truncDigits(inputNumber, digits) {
  const fact = 10 ** digits;
  return Math.floor(inputNumber * fact) / fact;
}

我的正數版本:

function toFixed_norounding(n,p)
{
    var result = n.toFixed(p);
    return result <= n ? result: (result - Math.pow(0.1,p)).toFixed(p);
}

快速、漂亮、明顯。 (正數版本)

我使用以下簡單方法進行了修復-

var num = 15.7784514;
Math.floor(num*100)/100;

結果將是15.77

這些解決方案確實有效,但對我來說似乎不必要地復雜。 我個人喜歡使用模運算符來獲得除法運算的余數,然后將其刪除。 假設 num = 15.7784514:

num-=num%.01;

這相當於說 num = num - (num % .01)。

這里的答案對我沒有幫助,它一直在四舍五入或給我錯誤的小數。

我的解決方案將您的小數轉換為字符串,提取字符,然后將整個內容作為數字返回。

function Dec2(num) {
  num = String(num);
  if(num.indexOf('.') !== -1) {
    var numarr = num.split(".");
    if (numarr.length == 1) {
      return Number(num);
    }
    else {
      return Number(numarr[0]+"."+numarr[1].charAt(0)+numarr[1].charAt(1));
    }
  }
  else {
    return Number(num);
  }  
}

Dec2(99); // 99
Dec2(99.9999999); // 99.99
Dec2(99.35154); // 99.35
Dec2(99.8); // 99.8
Dec2(10265.985475); // 10265.98

以下代碼對我來說非常有用:

num.toString().match(/.\*\\..{0,2}|.\*/)[0];

下一個簡單的方法是確保金額參數以字符串形式給出。

function truncate(amountAsString, decimals = 2){
  var dotIndex = amountAsString.indexOf('.');
  var toTruncate = dotIndex !== -1  && ( amountAsString.length > dotIndex + decimals + 1);
  var approach = Math.pow(10, decimals);
  var amountToTruncate = toTruncate ? amountAsString.slice(0, dotIndex + decimals +1) : amountAsString;  
  return toTruncate
    ?  Math.floor(parseFloat(amountToTruncate) * approach ) / approach
    :  parseFloat(amountAsString);

}

console.log(truncate("7.99999")); //OUTPUT ==> 7.99
console.log(truncate("7.99999", 3)); //OUTPUT ==> 7.999
console.log(truncate("12.799999999999999")); //OUTPUT ==> 7.99

這對我來說效果很好。 我希望它也能解決你的問題。

function toFixedNumber(number) {
    const spitedValues = String(number.toLocaleString()).split('.');
    let decimalValue = spitedValues.length > 1 ? spitedValues[1] : '';
    decimalValue = decimalValue.concat('00').substr(0,2);

    return '$'+spitedValues[0] + '.' + decimalValue;
}

// 5.56789      ---->  $5.56
// 0.342        ---->  $0.34
// -10.3484534  ---->  $-10.34 
// 600          ---->  $600.00

 function convertNumber(){ var result = toFixedNumber(document.getElementById("valueText").value); document.getElementById("resultText").value = result; } function toFixedNumber(number) { const spitedValues = String(number.toLocaleString()).split('.'); let decimalValue = spitedValues.length > 1 ? spitedValues[1] : ''; decimalValue = decimalValue.concat('00').substr(0,2); return '$'+spitedValues[0] + '.' + decimalValue; }
 <div> <input type="text" id="valueText" placeholder="Input value here.."> <br> <button onclick="convertNumber()" >Convert</button> <br><hr> <input type="text" id="resultText" placeholder="result" readonly="true"> </div>

給你。 一個答案顯示了解決問題的另一種方法:

// For the sake of simplicity, here is a complete function:
function truncate(numToBeTruncated, numOfDecimals) {
    var theNumber = numToBeTruncated.toString();
    var pointIndex = theNumber.indexOf('.');
    return +(theNumber.slice(0, pointIndex > -1 ? ++numOfDecimals + pointIndex : undefined));
}

請注意在最終表達式之前使用 +。 也就是將我們截斷、切片的字符串轉換回數字類型。

希望能幫助到你!

不帶零截斷

function toTrunc(value,n){  
    return Math.floor(value*Math.pow(10,n))/(Math.pow(10,n));
}

或者

function toTrunc(value,n){
    x=(value.toString()+".0").split(".");
    return parseFloat(x[0]+"."+x[1].substr(0,n));
}

測試:

toTrunc(17.4532,2)  //17.45
toTrunc(177.4532,1) //177.4
toTrunc(1.4532,1)   //1.4
toTrunc(.4,2)       //0.4

用零截斷

function toTruncFixed(value,n){
    return toTrunc(value,n).toFixed(n);
}

測試:

toTrunc(17.4532,2)  //17.45
toTrunc(177.4532,1) //177.4
toTrunc(1.4532,1)   //1.4
toTrunc(.4,2)       //0.40

如果您確實想截斷為 2 位精度,您可以使用一個簡單的邏輯:

function myFunction(number) {
  var roundedNumber = number.toFixed(2);
  if (roundedNumber > number)
  {
      roundedNumber = roundedNumber - 0.01;
  }
  return roundedNumber;
}

我使用(num-0.05).toFixed(1)來獲得第二個小數點。

不四舍五入得到兩個浮點數更可靠。

參考答案

 var number = 10.5859; var fixed2FloatPoints = parseInt(number * 100) / 100; console.log(fixed2FloatPoints);

謝謝你 !

我在 typescript 中的解決方案(可以很容易地移植到 JS):

/**
 * Returns the price with correct precision as a string
 *
 * @param   price The price in decimal to be formatted.
 * @param   decimalPlaces The number of decimal places to use
 * @return  string The price in Decimal formatting.
 */
type toDecimal = (price: number, decimalPlaces?: number) => string;
const toDecimalOdds: toDecimal = (
  price: number,
  decimalPlaces: number = 2,
): string => {
  const priceString: string = price.toString();
  const pointIndex: number = priceString.indexOf('.');

  // Return the integer part if decimalPlaces is 0
  if (decimalPlaces === 0) {
    return priceString.substr(0, pointIndex);
  }

  // Return value with 0s appended after decimal if the price is an integer
  if (pointIndex === -1) {
    const padZeroString: string = '0'.repeat(decimalPlaces);

    return `${priceString}.${padZeroString}`;
  }

  // If numbers after decimal are less than decimalPlaces, append with 0s
  const padZeroLen: number = priceString.length - pointIndex - 1;
  if (padZeroLen > 0 && padZeroLen < decimalPlaces) {
    const padZeroString: string = '0'.repeat(padZeroLen);

    return `${priceString}${padZeroString}`;
  }

  return priceString.substr(0, pointIndex + decimalPlaces + 1);
};

測試用例:

  expect(filters.toDecimalOdds(3.14159)).toBe('3.14');
  expect(filters.toDecimalOdds(3.14159, 2)).toBe('3.14');
  expect(filters.toDecimalOdds(3.14159, 0)).toBe('3');
  expect(filters.toDecimalOdds(3.14159, 10)).toBe('3.1415900000');
  expect(filters.toDecimalOdds(8.2)).toBe('8.20');

有什么改進嗎?

滾動你自己的toFixed函數:對於正值Math.floor工作正常。

function toFixed(num, fixed) {
    fixed = fixed || 0;
    fixed = Math.pow(10, fixed);
    return Math.floor(num * fixed) / fixed;
}

對於負值, Math.floor是值的四舍五入。 因此,您可以改用Math.ceil

例子,

Math.ceil(-15.778665 * 10000) / 10000 = -15.7786
Math.floor(-15.778665 * 10000) / 10000 = -15.7787 // wrong.

Gumbo 使用正則表達式的第二個解決方案確實有效,但由於正則表達式而運行緩慢。 由於浮點數不精確,Gumbo 的第一個解決方案在某些情況下會失敗。 有關演示和基准,請參閱JSFiddle 在我當前的系統 Intel Core i5-2500 CPU at 3.30 GHz 上,第二種解決方案每次調用大約需要 1636 納秒。

我寫的解決方案涉及添加一個小的補償來處理浮點不精確。 它基本上是瞬時的,即納秒級。 我每次調用計時 2 納秒,但 JavaScript 計時器不是非常精確或精細。 這是JS Fiddle和代碼。

function toFixedWithoutRounding (value, precision)
{
    var factorError = Math.pow(10, 14);
    var factorTruncate = Math.pow(10, 14 - precision);
    var factorDecimal = Math.pow(10, precision);
    return Math.floor(Math.floor(value * factorError + 1) / factorTruncate) / factorDecimal;
}

var values = [1.1299999999, 1.13, 1.139999999, 1.14, 1.14000000001, 1.13 * 100];

for (var i = 0; i < values.length; i++)
{
    var value = values[i];
    console.log(value + " --> " + toFixedWithoutRounding(value, 2));
}

for (var i = 0; i < values.length; i++)
{
    var value = values[i];
    console.log(value + " --> " + toFixedWithoutRounding(value, 4));
}

console.log("type of result is " + typeof toFixedWithoutRounding(1.13 * 100 / 100, 2));

// Benchmark
var value = 1.13 * 100;
var startTime = new Date();
var numRun = 1000000;
var nanosecondsPerMilliseconds = 1000000;

for (var run = 0; run < numRun; run++)
    toFixedWithoutRounding(value, 2);

var endTime = new Date();
var timeDiffNs = nanosecondsPerMilliseconds * (endTime - startTime);
var timePerCallNs = timeDiffNs / numRun;
console.log("Time per call (nanoseconds): " + timePerCallNs);

已經有一些適合正則表達式和算術計算的答案,你也可以試試這個

function myFunction() {
    var str = 12.234556; 
    str = str.toString().split('.');
    var res = str[1].slice(0, 2);
    document.getElementById("demo").innerHTML = str[0]+'.'+res;
}

// output: 12.23

基於大衛 D 的回答:

function NumberFormat(num,n) {
  var num = (arguments[0] != null) ? arguments[0] : 0;
  var n = (arguments[1] != null) ? arguments[1] : 2;
  if(num > 0){
    num = String(num);
    if(num.indexOf('.') !== -1) {
      var numarr = num.split(".");
      if (numarr.length > 1) {
        if(n > 0){
          var temp = numarr[0] + ".";
          for(var i = 0; i < n; i++){
            if(i < numarr[1].length){
              temp += numarr[1].charAt(i);
            }
          }
          num = Number(temp);
        }
      }
    }
  }
  return Number(num);
}

console.log('NumberFormat(123.85,2)',NumberFormat(123.85,2));
console.log('NumberFormat(123.851,2)',NumberFormat(123.851,2));
console.log('NumberFormat(0.85,2)',NumberFormat(0.85,2));
console.log('NumberFormat(0.851,2)',NumberFormat(0.851,2));
console.log('NumberFormat(0.85156,2)',NumberFormat(0.85156,2));
console.log('NumberFormat(0.85156,4)',NumberFormat(0.85156,4));
console.log('NumberFormat(0.85156,8)',NumberFormat(0.85156,8));
console.log('NumberFormat(".85156",2)',NumberFormat(".85156",2));
console.log('NumberFormat("0.85156",2)',NumberFormat("0.85156",2));
console.log('NumberFormat("1005.85156",2)',NumberFormat("1005.85156",2));
console.log('NumberFormat("0",2)',NumberFormat("0",2));
console.log('NumberFormat("",2)',NumberFormat("",2));
console.log('NumberFormat(85156,8)',NumberFormat(85156,8));
console.log('NumberFormat("85156",2)',NumberFormat("85156",2));
console.log('NumberFormat("85156.",2)',NumberFormat("85156.",2));

// NumberFormat(123.85,2) 123.85
// NumberFormat(123.851,2) 123.85
// NumberFormat(0.85,2) 0.85
// NumberFormat(0.851,2) 0.85
// NumberFormat(0.85156,2) 0.85
// NumberFormat(0.85156,4) 0.8515
// NumberFormat(0.85156,8) 0.85156
// NumberFormat(".85156",2) 0.85
// NumberFormat("0.85156",2) 0.85
// NumberFormat("1005.85156",2) 1005.85
// NumberFormat("0",2) 0
// NumberFormat("",2) 0
// NumberFormat(85156,8) 85156
// NumberFormat("85156",2) 85156
// NumberFormat("85156.",2) 85156

這是用字符串做的

export function withoutRange(number) {
  const str = String(number);
  const dotPosition = str.indexOf('.');
  if (dotPosition > 0) {
    const length = str.substring().length;
    const end = length > 3 ? 3 : length;
    return str.substring(0, dotPosition + end);
  }
  return str;
}

所有這些答案似乎都有些復雜。 我會從你的數字中減去 0.5 並使用 toFixed()。

另一種解決方案,截斷舍入

function round (number, decimals, truncate) {
    if (truncate) {
        number = number.toFixed(decimals + 1);
        return parseFloat(number.slice(0, -1));
    }

    var n = Math.pow(10.0, decimals);
    return Math.round(number * n) / n;
};

結合所有先前答案的知識,

這就是我想出的解決方案:

function toFixedWithoutRounding(num, fractionDigits) {
  if ((num > 0 && num < 0.000001) || (num < 0 && num > -0.000001)) {
    // HACK: below this js starts to turn numbers into exponential form like 1e-7.
    // This gives wrong results so we are just changing the original number to 0 here
    // as we don't need such small numbers anyway.
    num = 0;
  }
  const re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fractionDigits || -1) + '})?');
  return Number(num.toString().match(re)[0]).toFixed(fractionDigits);
}
function toFixed(num, fixed) {
    fixed = fixed || 0;
    var front = Math.floor(num);
    var back = 0;
    for (var i = 1; i <= fixed; i++) {
        var value = Math.floor(num * Math.pow(10, i)) % 10;
        back += value / Math.pow(10, i);
    }
    return front + back;
}

2021 年 6 月更新

這將修復具有給定長度的任何數字,而無需四舍五入

 let FixWithoutRounding = (v, l) => { const intPart = Math.trunc(v).toString() const fractionPart = v.toString().slice(v.toString().indexOf('.') + 1) if (fractionPart.length > l) { return Number(intPart.concat('.', fractionPart.slice(0, l))) } else { const padded = intPart.concat('.', fractionPart.padEnd(l, '0')) return padded } } console.log(FixWithoutRounding(123.123, 12))

最有效的解決方案(對於 2 個小數位)是在調用toFixed()之前減去 0.005

function toFixed2( num ) { return (num-0.005).toFixed(2) }

負數也將四舍五入(遠離零)。 OP沒有告訴任何關於負數的事情。

我知道已經有很少的工作示例,但我認為提出我的 String.toFixed 等效項是值得的,有些人可能會覺得它很有幫助。

這是我的 toFixed 替代方案,它不四舍五入,只是根據給定的精度截斷它或添加零。 對於超長數字,當精度太長時,它使用 JS 內置舍入。 函數適用於我在堆棧上找到的所有有問題的數字。

function toFixedFixed(value, precision = 0) {
    let stringValue = isNaN(+value) ? '0' : String(+value);

    if (stringValue.indexOf('e') > -1 || stringValue === 'Infinity' || stringValue === '-Infinity') {
        throw new Error('To large number to be processed');
    }

    let [ beforePoint, afterPoint ] = stringValue.indexOf('.') > -1 ? stringValue.split('.') : [ stringValue, ''];

    // Force automatic rounding for some long real numbers that ends with 99X, by converting it to string, cutting off last digit, then adding extra nines and casting it on number again
    // e.g. 2.0199999999999996: +('2.019999999999999' + '9999') will give 2.02
    if (stringValue.length >= 17 && afterPoint.length > 2 && +afterPoint.substr(afterPoint.length - 3) > 995) {
        stringValue = String(+(stringValue.substr(0, afterPoint.length - 1) + '9'.repeat(stringValue.split('.').shift().length + 4)));
        [ beforePoint, afterPoint ] = String(stringValue).indexOf('.') > -1 ? stringValue.split('.') : [ stringValue, ''];
    }

    if (precision === 0) {
        return beforePoint;
    } else if (afterPoint.length > precision) {
        return `${beforePoint}.${afterPoint.substr(0, precision)}`;
    } else {
        return `${beforePoint}.${afterPoint}${'0'.repeat(precision - afterPoint.length)}`;
    }
}

請記住,長度為 18 或更大的數字可能無法正確處理精度,例如 64 位 Chrome 將對其進行舍入或添加“e+”/“e-”以將數字的長度保持為 18。

如果您想對實數執行運算,則先將其乘以Math.sqrt(10, precision)會更安全,然后進行計算,然后將結果乘以乘數的值。

例子:

0.06 + 0.010.06999999999999999 ,並且每個非舍入的格式化函數都會將其截斷為0.06以獲得精度2

但是,如果您使用 multiplier&divider: (0.06 * 100 + 0.01 * 100) / 100執行相同的操作,您將得到0.07

這就是為什么在 javascript 中處理實數時使用這樣的乘數/除數非常重要,尤其是在計算金錢時......

一個簡單的解決方案

const toFixedNoRounding = (value, digits) => {
  const factor = Math.pow(10, digits);

  return Math.trunc(value * factor) / factor;
};

為了協作,我必須使用一個解決方案來處理比特幣數學運算。 關鍵是比特幣使用 8 個十進制數字,我們不需要四舍五入。

所以,我這樣做了:

  • 進行計算;

  • 取值並設置 9 個小數點

    值 = value.toFixed(9);

- 取截斷最后一個十進制數的子串:

value = value.substring(0, value.length - 1);

不,這並不優雅,但它是一個解決方案。

我遇到了同樣的問題,並決定在 TS 中使用字符串操作。

如果小數不足,則返回原值

const getDecimalsWithoutRounding = (value: number, numberOfDecimals: number) => {
  const stringValue: string = value?.toString();
  const dotIdx: number = stringValue?.indexOf('.');
  if (dotIdx) {
    return parseFloat(stringValue.slice(0, dotIdx + numberOfDecimals + 1));
  } else {
    return value;
  }
};

console.log(getDecimalsWithoutRounding(3.34589, 2)); /// 3.34
console.log(getDecimalsWithoutRounding(null, 2));  ///null
console.log(getDecimalsWithoutRounding(55.123456789, 5)); /// 55.12345
console.log(getDecimalsWithoutRounding(10, 2));  /// 10
console.log(getDecimalsWithoutRounding(10.6, 5)); /// 10.6


一個班輪

const formatPriceWithDecimal = (price: number) => 
                                parseInt(price * 10000)/10000).toFixed(2)
function FixWithoutRounding(number, digits) {
  var gbZero = '0000000000';
  var subNumber = number.toString().split('.');

  if (subNumber.length === 1)
    return [subNumber[0], '.', '0000'].join('');

  var result = '';
  if (subNumber[1].length > digits) {
    result = subNumber[1].substring(0, digits);
  } else {
    result = subNumber[1] + gbZero.substring(0, digits - subNumber[1].length);
  }

  return [subNumber[0], '.', result].join('');

}
function limitDecimalsWithoutRounding(val, decimals){
    let parts = val.toString().split(".");
    return parseFloat(parts[0] + "." + parts[1].substring(0, decimals));
}

var num = parseFloat(15.7784514);
var new_num = limitDecimalsWithoutRounding(num, 2);

謝謝馬丁·瓦穆斯

function floorFigure(figure, decimals){
     if (!decimals) decimals = 2;
     var d = Math.pow(10,decimals);
     return ((figure*d)/d).toFixed(decimals);
};

floorFigure(123.5999)    =>   "123.59"
floorFigure(123.5999, 3) =>   "123.599"

我做了一個簡單的更新,我得到了適當的四舍五入。 更新如下

return ((figure*d)/d).toFixed(decimals);

刪除 parseInt() 函數

這是另一種保存 .toFixed([digits]) 函數的變體,無需舍入浮點變量:

Number.prototype.toRealFixed = function(digits) {
    return Math.floor(this.valueOf() * Math.pow(10, digits)) / Math.pow(10, digits);
};

並調用:

var float_var = 0.02209062;
float_var.toRealFixed();

const toFixed = (value) => value.toString().slice(0,5);

暫無
暫無

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

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