// Example: toPrecision(4) when the number has 7 digits (3 before, 4 after)
// It will round to the tenths place
num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2
var price = 0.26453;
var priceRounded = Number((price).toFixed(2));
console.log('Original Price: ' + price);
console.log('Price Rounded: ' + priceRounded);
1
我找不到这个问题的准确解决方案,所以我创建了自己的:
function inprecise_round(value, decPlaces) {
return Math.round(value*Math.pow(10,decPlaces))/Math.pow(10,decPlaces);
}
function precise_round(value, decPlaces){
var val = value * Math.pow(10, decPlaces);
var fraction = (Math.round((val-parseInt(val))*10)/10);
//this line is for consistency with .NET Decimal.Round behavior
// -342.055 => -342.06
if(fraction == -0.5) fraction = -0.6;
val = Math.round(parseInt(val) + fraction) / Math.pow(10, decPlaces);
return val;
}
例子:
function inprecise_round(value, decPlaces) {
return Math.round(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}
function precise_round(value, decPlaces) {
var val = value * Math.pow(10, decPlaces);
var fraction = (Math.round((val - parseInt(val)) * 10) / 10);
//this line is for consistency with .NET Decimal.Round behavior
// -342.055 => -342.06
if (fraction == -0.5) fraction = -0.6;
val = Math.round(parseInt(val) + fraction) / Math.pow(10, decPlaces);
return val;
}
// This may produce different results depending on the browser environment
console.log("342.055.toFixed(2) :", 342.055.toFixed(2)); // 342.06 on Chrome & IE10
console.log("inprecise_round(342.055, 2):", inprecise_round(342.055, 2)); // 342.05
console.log("precise_round(342.055, 2) :", precise_round(342.055, 2)); // 342.06
console.log("precise_round(-342.055, 2) :", precise_round(-342.055, 2)); // -342.06
console.log("inprecise_round(0.565, 2) :", inprecise_round(0.565, 2)); // 0.56
console.log("precise_round(0.565, 2) :", precise_round(0.565, 2)); // 0.57
浮点值的问题在于它们试图用固定的位数表示无限量的(连续)值 . 所以很自然地,游戏中肯定会有一些损失,你会被一些 Value 观所困扰 .
当计算机将1.275存储为浮点值时,它赢得了't actually remember whether it was 1.275 or 1.27499999999999993, or even 1.27500000000000002. These values should give different results after rounding to two decimals, but they won't,因为对于计算机,它们在存储为浮点值后看起来完全相同,并且无法恢复丢失的数据 . 任何进一步的计算只会累积这种不精确性 .
function toDec(num, dec)
{
if(typeof dec=='undefined' || dec<0)
dec = 2;
var tmp = dec + 1;
for(var i=1; i<=tmp; i++)
num = num * 10;
num = num / 10;
num = Math.round(num);
for(var i=1; i<=dec; i++)
num = num / 10;
num = num.toFixed(dec);
return num;
}
fixPrecision: function (value) {
var me = this,
nan = isNaN(value),
precision = me.decimalPrecision;
if (nan || !value) {
return nan ? '' : value;
} else if (!me.allowDecimals || precision <= 0) {
precision = 0;
}
//[1]
//return parseFloat(Ext.Number.toFixed(parseFloat(value), precision));
precision = precision || 0;
var negMultiplier = value < 0 ? -1 : 1;
//[2]
var numWithExp = parseFloat(value + "e" + precision);
var roundedNum = parseFloat(Math.round(Math.abs(numWithExp)) + 'e-' + precision) * negMultiplier;
return parseFloat(roundedNum.toFixed(precision));
},
我也有代码评论(对不起,我已经忘记了所有细节)...我在这里发布我的答案以供将来参考:
9.995 * 100 = 999.4999999999999
Whereas 9.995e2 = 999.5
This discrepancy causes Math.round(9.995 * 100) = 999 instead of 1000.
Use e notation instead of multiplying /dividing by Math.Pow(10,precision).
/*Due to all told stuff. You may do 2 things for different purposes:
When showing/printing stuff use this in your alert/innerHtml= contents:
YourRebelNumber.toFixed(2)*/
var aNumber=9242.16;
var YourRebelNumber=aNumber-9000;
alert(YourRebelNumber);
alert(YourRebelNumber.toFixed(2));
/*and when comparing use:
Number(YourRebelNumber.toFixed(2))*/
if(YourRebelNumber==242.16)alert("Not Rounded");
if(Number(YourRebelNumber.toFixed(2))==242.16)alert("Rounded");
/*Number will behave as you want in that moment. After that, it'll return to its defiance.
*/
0
这非常简单,并且与其他任何一个一样有效:
function parseNumber(val, decimalPlaces) {
if (decimalPlaces == null) decimalPlaces = 0
var ret = Number(val).toFixed(decimalPlaces)
return Number(ret)
}
29 回答
Round down
Round up
Round nearest
要使用定点表示法格式化数字,只需使用toFixed方法:
请注意
toFixed()
返回一个字符串 .IMPORTANT :请注意,toFixed实际上并不是圆形的,90%的时间它会返回舍入值,但在很多情况下它实际上并不起作用 . 在您的控制台中试试这个:
2.005.toFixed(2)
你会得到错误的答案
在javascript中没有自然的方式来获得小数舍入,您将需要自己的polyfill或使用库 . 你可以看一下mozilla的polyfill https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
这是一个古老的主题,但仍然排名靠前的谷歌搜索结果和提供的解决方案共享相同的浮点小数问题 . 这是我使用的(非常通用)函数,thanks to MDN:
我们可以看到,我们没有遇到这些问题:
这种通用性也提供了一些很酷的东西:
现在,要回答OP的问题,必须输入:
或者,为了更简洁,更通用的功能:
你可以用它来调用它:
各种示例和测试(感谢@t-j-crowder!):
我通常将它添加到我的个人库中,经过一些建议并使用@TIMINeutron解决方案,然后使其适应小数长度,这个最适合:
将适用于所报告的例外情况 .
我不知道为什么我不能在之前的答案中添加评论(也许我绝对是盲目的,不知道),但我想出了一个使用@Miguel答案的解决方案:
它的两条评论(来自@bighostkim和@Imre):
问题
precise_round(1.275,2)
未返回1.28问题
precise_round(6,2)
未返回6.00(正如他所想) .我的最终解决方案如下:
正如你所看到的,我不得不添加一点"correction"(它不是它的原因,但是因为Math.round是有损的 - 你可以在jsfiddle.net上查看它 - 这是我知道如何"fix"它的唯一方法) . 它将已填充的数字加0.001,因此它在十进制值的右侧添加
1
三个0
. 所以它应该是安全的 .之后我添加
.toFixed(decimal)
以始终以正确的格式输出数字(使用正确的小数) .所以这就是它 . 好好用;)
编辑:为负数的“修正”增加了功能 .
一种方法是100%确定你得到一个2位小数的数字:
如果这导致舍入错误,您可以使用以下内容,正如詹姆斯在他的评论中所解释的那样:
请使用以下方法
如果你想要数字固定使用
使用这些示例,在尝试舍入数字1.005时仍会出现错误,解决方案是使用像Math.js这样的库或此函数:
这是我的1行解决方案: Number((yourNumericValueHere).toFixed(2));
这是发生的事情:
1)首先,将
.toFixed(2)
应用于要舍入小数位的数字 . 请注意,这会将值从数字转换为字符串 . 因此,如果您使用的是Typescript,它将抛出如下错误:“类型'字符串'不能指定为'数字'类型”
2)要获取数值或将字符串转换为数值,只需在所谓的'string'值上应用
Number()
函数 .有关说明,请查看以下示例:
EXAMPLE: 我的小数位数最多有5位数,我想把它缩短到2位小数 . 我是这样做的:
我找不到这个问题的准确解决方案,所以我创建了自己的:
例子:
@heridev和我在jQuery中创建了一个小函数 .
您可以尝试下一个:
HTML
jQuery的
在线演示:
http://jsfiddle.net/c4Wqn/
浮点值的问题在于它们试图用固定的位数表示无限量的(连续)值 . 所以很自然地,游戏中肯定会有一些损失,你会被一些 Value 观所困扰 .
当计算机将1.275存储为浮点值时,它赢得了't actually remember whether it was 1.275 or 1.27499999999999993, or even 1.27500000000000002. These values should give different results after rounding to two decimals, but they won't,因为对于计算机,它们在存储为浮点值后看起来完全相同,并且无法恢复丢失的数据 . 任何进一步的计算只会累积这种不精确性 .
因此,如果精度很重要,则必须从一开始就避免使用浮点值 . 最简单的选择是
使用devoted library
使用字符串存储和传递值(伴随字符串操作)
使用整数(例如,您可以传递实际值的百分之一,例如以美分而不是以美元计算的金额)
例如,当使用整数来存储百分之一时,查找实际值的函数非常简单:
使用字符串,您需要舍入,但它仍然可以管理:
请注意,此函数舍入到最接近,与零相关,而IEEE 754建议舍入到最近,甚至作为浮点运算的默认行为 . 这些修改留给读者练习:)
这是一个简单的
像
alert(roundFloat(1.79209243929,4));
一样使用Jsfiddle
舍入小数值,然后使用
toFixed(x)
作为预期的数字 .呼叫
parseDecimalRoundAndFixed(10.800243929,4)=> 10.80 parseDecimalRoundAndFixed(10.807243929,2)=>10.81
将 the following 放在某个全局范围内:
和 then try :
更新
请注意
toFixed()
只能用于_919950之间的小数位数,即a.getDecimals(25)
可能会生成javascript错误,因此为了适应您可以添加一些额外的检查,即这将返回1到100的随机数,四舍五入到小数点后两位 .
这对我有用:Rounding Decimals in JavaScript
通过引用使用此响应:https://stackoverflow.com/a/21029698/454827
我构建一个函数来获得动态的小数:
这里的工作示例:https://jsfiddle.net/wpxLduLc/
几个月前我从这篇文章中得到了一些想法,但这里没有答案,也没有其他帖子/博客的答案可以处理所有场景(例如我们的测试人员发现的负数和一些“幸运数字”) . 最后,我们的测试人员发现以下方法没有任何问题 . 粘贴我的代码片段:
我也有代码评论(对不起,我已经忘记了所有细节)...我在这里发布我的答案以供将来参考:
我解决了修饰符的问题 . Support 2 decimal only.
那会产生:
10.20
应该产生:
0.05
那会产生:
4.04
等等
这非常简单,并且与其他任何一个一样有效:
由于toFixed()只能在数字上调用,并且不幸地返回一个字符串,因此它会在两个方向上为您完成所有解析 . 你可以传递一个字符串或一个数字,每次都会得到一个数字!调用parseNumber(1.49)会给你1,而parseNumber(1.49,2)会给你1.50 . 就像他们最好的一样!
您也可以使用
.toPrecision()
方法和一些自定义代码,并且无论int部分的长度如何,始终向上舍入到第n个十进制数字 .你也可以把它作为一个插件,以便更好地使用 .
很简单 .
我发现了一种非常简单的方法可以解决这个问题,可以使用或改编:
100%工作!!!试试吧