固定不四舍五入

我使用 javascript 绑定到一些复选框,而 toFixed(2)并没有四舍五入。知道为什么没有四舍五入吗?例如,如果数字是 859.385,它只显示 859.38而不是 859.39

我也读到过 toFixed可以根据你使用的浏览器不同而不同,有人知道解决这个问题的方法吗? 这样我的 javascript 计算就可以和我的 php 计算相匹配?

var standardprice = parseFloat($('#hsprice_'+this.id.split('_')[1]).val());
var price =  parseFloat($('#hprice_'+this.id.split('_')[1]).val());
var discount =  parseFloat($('#hdiscount_'+this.id.split('_')[1]).val());
var deposit =  parseFloat($('#hdeposit_'+this.id.split('_')[1]).val());


var currSprice = parseFloat($('#hTotalSprice').val());
var currPrice = parseFloat($('#hTotalPrice').val());
var currDiscount = parseFloat($('#hTotalDiscount').val());
var currDeposit = parseFloat($('#hTotalDeposit').val());


currSprice += standardprice;
currPrice += price;
currDiscount += discount;
currDeposit += deposit;


$('#lblTotalSprice').text('$'+addCommas(currSprice.toFixed(2)));
$('#lblTotalPrice').text('$'+addCommas(currPrice.toFixed(2)));
$('#lblTotalDiscount').text('$'+addCommas(currDiscount.toFixed(2)));
$('#lblTotalDeposit').text('$'+addCommas(currDeposit.toFixed(2)));


$('#hTotalSprice').val(currSprice.toFixed(2));
$('#hTotalPrice').val(currPrice.toFixed(2));
$('#hTotalDiscount').val(currDiscount.toFixed(2));
$('#hTotalDeposit').val(currDeposit.toFixed(2));
111301 次浏览

您可以使用 Math.round()来四舍五入这个数字。如果你想四舍五入到一个特定的小数点,你可以使用一个小数学:

var result=Math.round(original*100)/100
function roundup(num,dec){
dec= dec || 0;
var  s=String(num);
if(num%1)s= s.replace(/5$/, '6');
return Number((+s).toFixed(dec));
}


var n= 35.855
roundup(n,2)

/* 返回值: (数字) 35.86 */

在 Chrome 中,toFixed()轮:

859.385 ==> 859.38
859.386 ==> 859.39

当我查看 .toFixed()的 ECMAScript 第5版规范(第15.7.4.5节)时,我没有看到它明确地描述舍入,尽管它确实相当隐晦地描述了一些可能是 Chrome 实现的东西。

在我看来,如果你想用显式舍入来控制它,那么你可能应该使用经常建议的解决方法:

var roundedNum = (Math.round( num * 100 ) / 100).toFixed(2);

这将保证您得到可预测的舍入,就像您习惯的那样。

工作演示: http://jsfiddle.net/jfriend00/kvpgE/

这个可能会有帮助

    tofix2Decimals=function(float){
if(parseInt(float)==float)return float.toFixed(2);
$decimals=/\.(\d+)/.exec(float)[1].length;
$decimals=$decimals>=2?$decimals+1:3;
float+=Math.pow(10,-$decimals);
return float.toFixed(2);
}

我偶然发现了这个问题,想知道为什么 Number.toFixed的表现很奇怪。我发现原生函数不可靠,这很不幸。出于好奇,我仔细查看了答案,发现大部分答案都不符合 35.855这个数字,而 T.J。克劳德对每个答案都慷慨地做出了评论。

也许这能回答你的问题。

function toFixed(n,precision) {
var match=RegExp("(\\d+\\.\\d{1,"+precision+"})(\\d)?").exec(n);
if(match===null||match[2]===undefined) {
return n.toFixed(precision);
}
if(match[2]>=5) {
return (Number(match[1])+Math.pow(10,-precision)).toFixed(precision);
}
return match[1];
}

正则表达式将数字分割成字符串数组,如 toFixed(35.855,2): ["35.855", "35.85", "5"]。如果最后一个数字(在精度截止值之后)是 >=5,则将 Math.pow(10, -precision)添加到修剪后的数字中。这将添加 .01,如果你在2小数点截断,.002在3,等等。

我不知道这是否万无一失,因为它仍然可以对不可预测的浮点数进行十进制计算。我可以说它从 35.85535.86

这是由于 JavaScript 的浮点表示法造成的。

试试这个:

Number.prototype.round = function(digits) {
digits = Math.floor(digits);
if (isNaN(digits) || digits === 0) {
return Math.round(this);
}
if (digits < 0 || digits > 16) {
throw 'RangeError: Number.round() digits argument must be between 0 and 16';
}
var multiplicator = Math.pow(10, digits);
return Math.round(this * multiplicator) / multiplicator;
}


Number.prototype.fixed = function(digits) {
digits = Math.floor(digits);
if (isNaN(digits) || digits === 0) {
return Math.round(this).toString();
}
var parts = this.round(digits).toString().split('.');
var fraction = parts.length === 1 ? '' : parts[1];
if (digits > fraction.length) {
fraction += new Array(digits - fraction.length + 1).join('0');
}
return parts[0] + '.' + fraction;
}

用法:

var n = 859.385;
console.log(n.round(2)); // 859.39
console.log(n.fixed(2)); // 859.39
console.log(n.round(4)); // 859.385
console.log(n.fixed(4)); // 859.3850

与35.855一起尝试的另一个好数字是1.005

我不认为 Robert Messerle 的解决方案能解决1.005

这里的舍入小数示例 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round $version/1383484 # Decimal _ round 将数字转换为指数符号,似乎得到了更好的结果。

我在这里创建了一个小提琴 http://jsfiddle.net/cCX5y/2/,演示了上面的本地示例 Robert Messerle (称为 toFixedB)和 Mozilla docs (称为 toFixed10)。

我还没有找到一个数字是 Fixed10做错的。还有人能吗?

我还没有找到一个数字是 Fixed10做错的。还有人能吗?

感谢 blg他的回答指引我使用 Mozilla 的 ToFixed10()方法。

利用这一点,我想出了这个简短的一行,这确实涵盖了所有的情况下提到这里..。

function toFixed( num, precision ) {
return (+(Math.round(+(num + 'e' + precision)) + 'e' + -precision)).toFixed(precision);
}

我今天碰到了同样的问题,甚至在其他答案中尝试建议,我发现我仍然没有得到我期望的结果。最后,当我在当前的项目中使用 AngularJS 时,我想我应该检查一下 AngularJS 是否已经解决了同样的问题,而且他们确实解决了。下面是他们使用的解决方案,对我来说非常有效:

function toFixed(number, fractionSize) {
return +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
}

在这里发现: AngularJS filters.js 源代码

我做了这个在所有的财务数据作为一个最佳舍入函数使用。您可以对所有有问题的数字进行测试。Javascript 允许某种程度的精确性,所以我使用它来使几乎每个数字都像预期的那样进行舍入。

function roundTo(n, digits) {
if (digits === undefined) {
digits = 0;
}


var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
return Math.round(n) / multiplicator;
}

因为在 javascript 的 tofix- 函数中,浮点数字 5不属于整数的上半部分,所以如果你有这样的数字,给定的数字是四舍五入的:

859.385.toFixed(2) // results in 859.38

事实上,你可以在后面加上浮点数(零除外) ,比如:

859.3851.toFixed(2) // results in 859.39

因此,开发人员倾向于添加像 0.00000000001这样的数字,以便对其进行适当的舍入,并且不会意外地改变数字的值。

所以我想出了一个函数,它可以根据浮点数固定的位数来添加这样一个数字:

    // both parameters can be string or number
function toFixed(number, decimals) {
var x = Math.pow(10, Number(decimals) + 1);
return (Number(number) + (1 / x)).toFixed(decimals)
}
toFixed(859.385, 2) //results in 859.39

如果你想得到 作为输出的数字,那么在其他答案中考虑 Math.round()技术。

但是如果你想得到 作为输出的字符串,用于呈现给人类,那么通常 n.toLocaleString()n.toFixed()更有帮助。

为什么?因为它还会在大数字的头部添加逗号或句号,这是人们用来阅读的。例如:

var n = 1859.385


n.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})


// Produces  1,859.39  in USA (locale en-US)
// Produces  1 859,39  in France (locale fr-FR)
// Produces  1.859,39  in Germany (locale de-DE)

规范指出,当传递 undefined作为第一个参数时,将使用用户自己的区域设置(由操作系统指定)。遗憾的是,正如链接文档所示,Mozilla 在这种情况下使用 en-US 语言环境,但将来可能会遵守规范。

这里的答案应该是最好的答案,而不是这么多的黑客周围。

   x = 1859.385;
x = x.toFixed(2);
alert(x);

给出了一个错误的四舍五入(即1859.38而不是1859.39)

 x = 1859.385;
x = x.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
alert(x);

正确的四舍五入为1,859.39

唯一的问题是返回的结果是一个带有千逗号分隔符的字符串,因此不能用于计算。使用从堆栈溢出获得的 regex 删除逗号,最终结果是

 x = 1859.385;
x = x.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
x=x.replace(/\,/g,'');
alert(x);

现在返回1859.39可以用来计算。 Regex 即1,859.39之前的值可用于 html 显示,而未格式化的值1859.39可用于计算。

我知道这是一个古老的问题,但为什么不这样做:

let TruncatedValueInString = ThenNumberYouWantToTruncate.toFixed(decPlaces + 1).slice(0, -1);

toFixed()工作正常! 问题是,859.385在计算机上没有浮点数的表示形式。它被扫描为最接近的可能值 = 859.384999999999991。将这个值四舍五入到2位是859.38,而不是859.39。

这就是为什么许多编程语言(特别是旧的商业语言,如 COBOL)支持 BCD 数字(二进制编码的小数) ,其中每个数字自己被编码成4位(像不使用 A-F 的十六进制)。

一个通用的价格解决方案: 计算分/分和打印数字/100。

其他解决方案的说明(此处提供的函数) : 它们可能对某些数字有帮助,但多数情况下对859.38499999等数字没有帮助。

toFixed从来就不是 四舍五入也不是为它而生的。

它几乎不将浮点数(指数、尾数)转换为定点数(整数、小数)(参见 定义)。

虽然这样做,它可能看起来像四舍五入,因为 圆的数字是最接近原来的浮点表示。

遗憾的是,toFixed可以用于舍入的说法广为流传... ... 不,它不能,即使名字暗示与它没有任何关系。

如果你需要四舍五入加上 toFixed填充:

function round(num, precision) {
var base = 10 ** precision;
return (Math.round(num * base) / base).toFixed(precision);
}

我从 林伟力公司得到了合适的解决方案

function round(number, precision) {
var shift = function (number, exponent) {
var numArray = ("" + number).split("e");
return +(numArray[0] + "e" + (numArray[1] ? (+numArray[1] + exponent) : exponent));
};
return shift(Math.round(shift(number, +precision)), -precision);
}

测试结果

round(1.050, 1); // expected 1.1 , result 1.1  (correct)
round(1.005, 2); // expected 1.01, result 1.01 (correct)


round(3456.3456,  3); // 3456.346
round(3456.3456,  2); // 3456.35
round(3456.3456,  1); // 3456.3
round(3456.3456,  0); // 3456
round(3456.3456, -1); // 3460
round(3456.3456, -2); // 3500
round(3456.3456, -3); // 3000


round(undefined, 1        ); // NaN
round(null     , 1        ); // NaN
round("a"      , 1        ); // NaN
round(1        , null     ); // NaN
round(1        , undefined); // NaN
round(1        , "a"      ); // NaN

我想要的东西简洁,准确与可读性和速度的良好结合。在阅读了这个问题的所有答案和 这个特别有用的答案在一个类似的问题之后,这就是我的解决方案。

const round = (numberToRound, digits = 0, toFixed = false) => {
const precision = 10 ** digits;
const n = numberToRound * precision * (1 + Number.EPSILON);
const roundedNumber = Math.round(n) / precision;
return toFixed ? roundedNumber.toFixed(digits) : roundedNumber;
};


// rounding by half
console.log(round(0.5));
console.log(round(-0.5));


// fixed decimals
console.log(round(0.5, 2), '( Type:',typeof round(0.5, 2), ')');
console.log(round(0.5, 2, true), '( Type:',typeof round(0.5, 2, true), ')');
console.log(round(-0.5, 2), '( Type:',typeof round(-0.5, 2), ')');
console.log(round(-0.5, 2, true), '( Type:',typeof round(-0.5, 2, true), ')');


// edge cases
console.log(round(1.005, 2) === 1.01);
console.log(round(-1.005, 2) === -1.01);
console.log(round(39.425, 2) === 39.43);
console.log(round(-39.425, 2) === -39.43);
console.log(round(1234.00000254495, 10) === 1234.000002545);
console.log(round(-1234.00000254495, 10) === -1234.0000025449);


// edge cases from other answer's comments.
console.log(round(859.385, 2));
console.log(round(859.3844, 2));
console.log(round(0.000000015, 8))
console.log(round(35.855, 2));

我不喜欢 toFixed作为一个布尔参数,但是它现在起作用了。

function toFixed(num, decimals) {
return (Math.round((num + Number.EPSILON) * Math.pow(10, decimals)) / Math.pow(10, decimals)).toFixed(decimals)
}

我在这里找到了一个有效的答案-> 四舍五入到最多小数点后2位(只有在必要时)

Math.round((num + Number.EPSILON) * 100) / 100

您必须将 Number.EPSILON加入到整数中。

这是我的解决方案,包括3个特性。

  1. 正确的集合。
  2. 只以数字显示。 (预防科学记数法)
  3. 删除后面的零。

我把@user2823670的 回答这个结合在一起。

var roundUp = function(num, precision) {
// Return '' if num is empty string
if (typeof num === 'string' && !num) return '';


// Remove exponential notation
num = toPlainString(num);


// Fixed round up
var result = +((+(Math.round(+(num + 'e' + precision)) + 'e' + -precision)).toFixed(precision));


// Remove exponential notation (once again)
result = toPlainString(result);


return result;
};


var toPlainString = function(num) {
return ('' + num).replace(/(-?)(\d*)\.?(\d+)e([+-]\d+)/,
function(a, b, c, d, e) {
return e < 0
? b + '0.' + Array(1 - e - c.length).join(0) + c + d
: b + c + d + Array(e - d.length + 1).join(0);
}
);
}

注意: 您可能只需要这个.toFixed()解决方案来处理非常大的数字

其他公布的解决方案工作良好的标准数字(以下1e21)

如果你想要 处理非常大的数和非常小的分数toFixed有正确的舍入和没有准确性的损失,而不需要使用库和自包含的功能,一个可能的有效的解决方案是利用 BigInt,以避免由于内部 javascript 舍入造成的准确性损失。

toFixed(number, [digits])下面的函数执行此操作。

只需将大数字作为一个字符串传递,并附上所需的四舍五入数字。数字将被正确地四舍五入。

这个概念是一种常见的方法,将数字分为整个部分和小数部分,但使用 BigInt()保持这两个部分。然后,对正数和负数进行必要的舍入和处理,而不使用任何 javascript Math或数字函数,以避免失去准确性。

对于非常特殊的情况,数字是一个非常大的‘ e’符号,作为一个额外的好处,我添加了我在这里发布的 eToNumber()函数: https://stackoverflow.com/a/66072001/11606728作为一个内联进程。如果您想要维护短代码,并且不需要关心这些数字,那么可以删除这些代码。[代码中提供了注释来删除它]。

我已经包含了各种测试用例来测试不同的可能性(其中一些有点奇怪,但仍然会发生)。

这个想法可以进一步改进。

希望有用。

/****************************************************************************
* @function    : toFixed(number, [digits])
* @purpose     : Emulate toFixed() for large numbers and
large fractional numbers with correct rounding
by using the BigInt() built-in Object.
* @version     : 1.01
* @author      : Mohsen Alyafei
* @date        : 03 February 2021
* @param       : {number} [numeric or string] pass large numbers as a string
* @param       : {number} [optional digits]
*              : The number of digits to appear after the decimal point;
*              : this may be a value from 0 and above unlimited.
*              : If this argument is omitted or is negative, it is treated as 0.
*              : Handles large 'e' notation number using the eToNumber() function.digits
*              : See https://stackoverflow.com/a/66072001/11606728
* @returns     : A string representing the given number using fixed-point notation.
****************************************************************************/


function toFixed(num,digits) {
if (!num && num!==0) return "Cannot read property of null or undefined"; // Can change it to throw Error
digits<0 && (digits=0);
digits=digits||0;
num=eToNumber(num); // Delete this line and function below if larage 'e' notation number are not required
let wh = (num+="").split((.1).toLocaleString().substr(1,1)), f = wh[1];
wh = wh[0];
let fr = (f=f||"0").substr(0,digits), fn = BigInt(fr), w = BigInt(wh), fl = (""+fn).length,
lZeros = fr.length-fl, minus = wh[0]=="-", inc = (wh<0 || minus) ? BigInt(-1):BigInt(1);
f[digits]>=5 && (fn+=BigInt(1));
(fn+="").length > fl && (lZeros-=1);
lZeros >=0 ? lZeros="0".repeat(lZeros):(fn=fn.substring(1), lZeros="",
(fn ? w +=inc : ((f[digits]>=5) && (w+=inc))));
fn = lZeros + fn; L = digits-fn.length;
L && (fn+="0".repeat(L)); w==0 && minus && (w="-"+w);
return w+(fn?".":"")+fn;
}


//---------------------- Extra Function if needed --------------------------------
// Delete this function if large 'e' notation number are not required
// Convert very large 'e' numbers to plain string numbers.
//--------------------------------------------------------------------------------
function eToNumber(num) {
let sign="";
(num+="").charAt(0)=="-" && (num=num.substring(1),sign ="-");
let arr = num.split(/[e]/ig); if (arr.length<2) return sign+num;
let dot=(.1).toLocaleString().substr(1,1), n = arr[0], exp = +arr[1];
let w = (n=n.replace(/^0+/,'')).replace(dot,''),
pos = n.split(dot)[1]? n.indexOf(dot)+exp : w.length+exp,
L = pos-w.length,s=""+BigInt(w);
w = exp>=0 ? (L>=0 ? s+"0".repeat(L):r()): (pos<=0 ? "0"+dot+"0".repeat(Math.abs(pos))+s:r());
if (!+w) w=0; return sign+w;
function r(){return w.replace(new RegExp(`^(.{${pos}})(.)`),`$1${dot}$2`)}}


//================================================
//             Test Cases
//================================================
let r=0; // test tracker
r |= test(35.855,2,"35.86");
r |= test(12.00000015,2,"12.00");
r |= test(35.855,5,"35.85500");
r |= test(35.855,4,"35.8550");
r |= test(1.135,2,"1.14");
r |= test(1.135,3,"1.135");
r |= test(1.135,4,"1.1350");
r |= test(1.135,8,"1.13500000");
r |= test(0.1545,3,"0.155");
r |= test(89.684449,2,"89.68");
r |= test("0.0000001",2,"0.00");
r |= test("0.9993360575508052",3,"0.999");
r |= test("0.999336057550805244545454545",29,"0.99933605755080524454545454500");
r |= test("1.0020739645577939",3,"1.002");
r |= test(0.999,0,"1");
r |= test(0.999,1,"1.0");
r |= test(0.999,2,"1.00");
r |= test(0.975,0,"1");
r |= test(0.975,1,"1.0");
r |= test(0.975,2,"0.98");
r |= test(2.145,2,"2.15");
r |= test(2.135,2,"2.14");
r |= test(2.34,1,"2.3");
r |= test(2.35,1,"2.4");
r |= test("0.0000001",2,"0.00");
r |= test("0.0000001",7,"0.0000001");
r |= test("0.0000001",8,"0.00000010");
r |= test("0.00000015",2,"0.00");
if (r==0) console.log("Tests 01. Standard fractional numbers passed");
//================================================
r=0; // test tracker
r |= test("1234567890123456789444.99",5,"1234567890123456789444.99000");
r |= test("1234567890123456789444.1445",3,"1234567890123456789444.145");
r |= test("1234567890123456789444.14451445144514451745",19,"1234567890123456789444.1445144514451445175");
if (r==0) console.log("Tests 02. Large fractional numbers passed");
//================================================
r=0; // test tracker
r |= test(100,2,"100.00");
r |= test(0,5,"0.00000");
if (r==0) console.log("Tests 03. Non-fractional numbers passed");
//================================================
r=0; // test tracker
r |= test(12345.6789,null,"12346");
r |= test(2.1234,null,"2");
r |= test(12345.6789,undefined,"12346");
r |= test(2.1234,undefined,"2");
r |= test(12345.6789,"","12346");
r |= test(0.1234,"","0");
r |= test(2.1234,"","2");
if (r==0) console.log("Tests 04. Undefined, Null, and Empty Digits passed");
//================================================
r=0; // test tracker
r |= test(1.1155,2,"1.12");
r |= test(1.255,2,"1.26");
r |= test(1.265,2,"1.27");
r |= test(1.275,2,"1.28");
r |= test(1.285,2,"1.29");
r |= test(1.295,2,"1.30");
r |= test(2.05,1,"2.1");
r |= test(2.15,1,"2.2");
r |= test(2.55,1,"2.6");
r |= test(2.65,1,"2.7");
r |= test(2.215,2,"2.22");
r |= test(2.315,2,"2.32");
r |= test(2.715,2,"2.72");
r |= test(2.815,2,"2.82");
r |= test(2.005,2,"2.01");
r |= test(2.105,2,"2.11");
r |= test(2.405,2,"2.41");
r |= test(2.505,2,"2.51");
r |= test(2.605,2,"2.61");
r |= test(2.905,2,"2.91");
r |= test(0.00155,4,"0.0016");
r |= test(2.55,1,"2.6");
r |= test(-2.35,1,"-2.4");
if (r==0) console.log("Tests 05. Correct rounding passed");
//================================================
r=0; // test tracker
r |= test(-1.125,2,"-1.13");
r |= test(-1.15,1,"-1.2");
r |= test(-1.15,1,"-1.2");
r |= test(-1.45,1,"-1.5");
r |= test(-1.65,1,"-1.7");
r |= test(-1.95,1,"-2.0");
r |= test(-2.34,1,"-2.3");
r |= test("-0.024641163062896567",3,"-0.025");
r |= test("-0.024641163062896567",16,"-0.0246411630628966");
r |= test("0.024641163062896567",16, "0.0246411630628966");
r |= test("-0.0246411630628965",16,"-0.0246411630628965");
if (r==0) console.log("Tests 06. Negative numbers rounding passed");
//================================================
r=0; // test tracker
r |= test(.135,2,"0.14");    // without whole part
r |= test(-.135,2,"-0.14");
r |= test("+35.855",2,"35.86");
r |= test("0.0",2,"0.00");
r |= test("-0",2,"-0.00");       //minus 0
r |= test("-0.0",5,"-0.00000");  // minus 0
r |= test("",5,"Cannot read property of null or undefined");        // empty string
r |= test(null,5,"Cannot read property of null or undefined");      //null
r |= test(undefined,5,"Cannot read property of null or undefined"); // undefined
if (r==0) console.log("Tests 07. Special test cases passed");
//================================================
r=0; // test tracker
r |= test(1.1234e1,2,"11.23");      //11.234
r |= test(1.12e2,2,"112.00");       //112
r |= test(-1.1234e2,2,"-112.34");   // -112.34
r |= test(-1.1234e2,4,"-112.3400"); // -112.34
r |= test(-1.1235e2,2,"-112.35");   // -112.35
r |= test(-1.1235e2,1,"-112.4");    // -112.4
if (r==0) console.log("Tests 08. Standard e notation numbers passed");
//================================================


r=0; // test tracker
r |= test("123456789123456789.111122223333444455556666777788889999e+10",16,"1234567891234567891111222233.3344445555666678");
r |= test("1.1235678944556677e2",20,"112.35678944556677000000");
r |= test("99.1235678944556677e2",20,"9912.35678944556677000000");
if (r==0) console.log("Tests 09. Large e notation numbers passed");
//================================================


if (r==0) console.log(`${"-".repeat(22)}\nAll Test Cases Passed.\n${"-".repeat(22)}`);


//================================================
//             Test function
//================================================
function test(n1,n2,should) {
let result = toFixed(n1,n2);
if (result !== should) {console.log(`Output   : ${result}\nShould be: ${should}`);return 1;}
}

这招对我很管用“骇客”

function customTofix(value, precision) {
let decimalVal = 0;
    

if (value !== null) {
let appendValue = (((value - Math.floor(value)) !== 0) ? (precision <= (value.toString().split(".")[1].length || 0)) ? '1' : '' : '');
decimalVal = parseFloat(value.toString() + appendValue).toFixed(precision)
}


return decimalVal
}

我的锻炼方式:

对我来说,这足以包含在常见的 javascript 中,比如 helpers.js

// eslint-disable-next-line no-extend-native
Number.prototype.toFixed = function (fractionDigits) {
var precisionTens = Math.pow(10, fractionDigits || 0);
return (Math.round(Number(this) * precisionTens) / precisionTens);
}

这将覆盖原生的 javascript toFixed()原型函数。