假设我有一个值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?


当前回答

我的解决方案在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');

任何改善吗?

其他回答

不舍入得到两个浮点数更可靠。

参考答案

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

谢谢你!

为了合作,我必须使用比特币数学运算的解决方案。关键是比特币使用8个十进制数,我们不需要整数。

所以,我这样做了:

进行计算; 取这个值并设置9个小数 value = value. tofixed (9);

-去掉最后一个十进制数的子字符串:

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

不。这并不优雅,但它是一个解决方案。

这是用字符串做的

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;
}

这并不是一个安全的替代方法,因为许多其他的例子都将数字转换为指数符号,这个函数没有覆盖这个场景

// 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

下面是一种简单的方法,但必须确保amount参数以字符串形式给出。

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