This question already has an answer here:
这个问题已经有了答案:
- Round to at most 2 decimal places (only if necessary) 51 answers
- 最多小数点后2位(仅在必要时),51个答案。
I have the below JavaScript syntax:
下面是JavaScript语法:
var discount = Math.round(100 - (price / listprice) * 100);
This rounds up to the whole number, how can I return the result with two decimal places?
这是整数的整数倍,我怎样才能把结果返回小数点后两位呢?
13 个解决方案
#1
579
NOTE - See Edit 4 if 3 digit precision is important
注意-如果3位精度很重要,请参见编辑4。
var discount = (price / listprice).toFixed(2);
toFixed will round up or down for you depending on the values beyond 2 decimals.
根据两个小数点后的值,toFixed将会上下移动。
Example: http://jsfiddle.net/calder12/tv9HY/
例如:http://jsfiddle.net/calder12/tv9HY/
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
Edit - As mentioned by others this converts the result to a string. To avoid this:
编辑-正如其他人所提到的,它将结果转换为字符串。为了避免这种情况:
var discount = +((price / listprice).toFixed(2));
Edit 2- As also mentioned in the comments this function fails in some precision, in the case of 1.005 for example it will return 1.00 instead of 1.01. If accuracy to this degree is important I've found this answer: https://*.com/a/32605063/1726511 Which seems to work well with all the tests I've tried.
编辑2-正如在注释中提到的,这个函数在某些精度上失败了,例如在1.005的情况下,它将返回1.00而不是1.01。如果这个学位的精确度很重要,我已经找到了这个答案:https://*.com/a/32605063/1726511,它似乎与我尝试过的所有测试都很好。
There is one minor modification required though, the function in the answer linked above returns whole numbers when it rounds to one, so for example 99.004 will return 99 instead of 99.00 which isn't ideal for displaying prices.
虽然需要进行一个小的修改,但是在返回的结果中,这个函数会返回整数,因此,例如99.004将返回99,而不是99.00,这并不适合显示价格。
Edit 3 - Seems having the toFixed on the actual return was STILL screwing up some numbers, this final edit appears to work. Geez so many reworks!
编辑3 -似乎在实际的返回上固定了一些数字,这最后的编辑似乎起作用了。天啊这么多的重做!
var discount = roundTo((price / listprice), 2);
function roundTo(n, digits) {
if (digits === undefined) {
digits = 0;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
var test =(Math.round(n) / multiplicator);
return +(test.toFixed(digits));
}
See Fiddle example here: https://jsfiddle.net/calder12/3Lbhfy5s/
参见这里的小提琴示例:https://jsfiddle.net/calder12/3Lbhfy5s/。
Edit 4 - You guys are killing me. Edit 3 fails on negative numbers, without digging into why it's just easier to deal with turning a negative number positive before doing the rounding, then turning it back before returning the result.
编辑4 -你们杀了我。编辑3在负数上失败,没有深入探究为什么在做四舍两入之前,处理一个负数的正数更容易,然后在返回结果之前把它转回来。
function roundTo(n, digits) {
var negative = false;
if (digits === undefined) {
digits = 0;
}
if( n < 0) {
negative = true;
n = n * -1;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
n = (Math.round(n) / multiplicator).toFixed(2);
if( negative ) {
n = (n * -1).toFixed(2);
}
return n;
}
Fiddle: https://jsfiddle.net/3Lbhfy5s/79/
小提琴:https://jsfiddle.net/3Lbhfy5s/79/
#2
116
If you use a unary plus to convert a string to a number as documented on MDN.
如果使用unary plus将字符串转换为MDN上记录的数字。
For example:+discount.toFixed(2)
例如:+ discount.toFixed(2)
#3
34
The functions Math.round() and .toFixed() is meant to round to the nearest integer. You'll get incorrect results when dealing with decimals and using the "multiply and divide" method for Math.round() or parameter for .toFixed(). For example, if you try to round 1.005 using Math.round(1.005 * 100) / 100 then you'll get the result of 1, and 1.00 using .toFixed(2) instead of getting the correct answer of 1.01.
函数Math.round()和. tofixed()的意思是四舍五入到最接近的整数。使用Math.round()或参数for . tofixed()时,处理小数和使用“乘法和分隔”方法时,会得到不正确的结果。例如,如果您试图使用Math.round(1.005 * 100) / 100来尝试使用1.005,那么您将得到1和1.00使用. tofixed(2)的结果,而不是得到1.01的正确答案。
You can use following to solve this issue:
你可以用以下方法来解决这个问题:
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2');
Add .toFixed(2) to get the two decimal places you wanted.
加上。tofixed(2)得到你想要的两个小数点。
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2').toFixed(2);
You could make a function that will handle the rounding for you:
你可以做一个函数来处理你的四舍五入:
function round(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
Example: https://jsfiddle.net/k5tpq3pd/36/
例如:https://jsfiddle.net/k5tpq3pd/36/
Alternativ
Alternativ
You can add a round function to Number using prototype. I would not suggest adding .toFixed() here as it would return a string instead of number.
您可以使用原型添加一个圆形函数到数字。我不建议在这里添加. tofixed(),因为它将返回一个字符串而不是number。
Number.prototype.round = function(decimals) {
return Number((Math.round(this + "e" + decimals) + "e-" + decimals));
}
and use it like this:
然后像这样使用:
var numberToRound = 100 - (price / listprice) * 100;
numberToRound.round(2);
numberToRound.round(2).toFixed(2); //Converts it to string with two decimals
Example https://jsfiddle.net/k5tpq3pd/35/
比如https://jsfiddle.net/k5tpq3pd/35/
Source: http://www.jacklmoore.com/notes/rounding-in-javascript/
来源:http://www.jacklmoore.com/notes/rounding-in-javascript/
#4
27
To get the result with two decimals, you can do like this :
为了得到两个小数的结果,你可以这样做:
var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;
The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result.
取整数的值乘以100,保持前两个数字,然后除以100得到实际结果。
#5
13
try using discount.toFixed(2);
试着用discount.toFixed(2);
#6
7
A small variation on the accepted answer. toFixed(2)
returns a string, and you will always get two decimal places. These might be zeros. If you would like to suppress final zero(s), simply do this:
在接受的答案上有一个小的变化。toFixed(2)返回一个字符串,您将总是得到两个小数点。这些可能是零。如果你想要压制最后的零点,只要这样做:
var discount = + ((price / listprice).toFixed(2));
Edited: I've just discovered what seems to be a bug in Firefox 35.0.1, which means that the above may give NaN with some values.
I've changed my code to
编辑:我刚刚在Firefox 35.0.1中发现了一个bug,这意味着上面可能会给NaN一些值。我把代码改了。
var discount = Math.round(price / listprice * 100) / 100;
This gives a number with up to two decimal places. If you wanted three, you would multiply and divide by 1000, and so on.
The OP wants two decimal places always, but if toFixed() is broken in Firefox it needs fixing first.
See https://bugzilla.mozilla.org/show_bug.cgi?id=1134388
这给出了一个小数点后两位的数字。如果你想要三个,你可以乘上,除以1000,以此类推。OP总是需要两个小数点,但如果在Firefox中使用toFixed(),则需要先修复。参见https://bugzilla.mozilla.org/show_bug.cgi?id=1134388
#7
7
The best and simple solution I found is
我找到的最好和最简单的解决办法是。
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // 1.01
Reference: http://www.jacklmoore.com/notes/rounding-in-javascript/
参考:http://www.jacklmoore.com/notes/rounding-in-javascript/
#8
7
I think the best way I've seen it done is multiplying by 10 to the power of the number of digits, then doing a Math.round, then finally dividing by 10 to the power of digits. Here is a simple function I use in typescript:
我认为我看到的最好的方法是乘以10的数次方,然后做一个数学运算。圆,最后除以10的数次方。这是我在打字稿中使用的一个简单的函数:
function roundToXDigits(value: number, digits: number) {
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
Or plain javascript:
或纯javascript:
function roundToXDigits(value, digits) {
if(!digits){
digits = 2;
}
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
#9
5
Fastest Way - faster than toFixed():
最快的方式-比固定()更快:
TWO DECIMALS
x = .123456
result = Math.round(x * 100) / 100 // result .12
THREE DECIMALS
x = .123456
result = Math.round(x * 1000) / 1000 // result .123
#10
2
function round(num,dec)
{
num = Math.round(num+'e'+dec)
return Number(num+'e-'+dec)
}
//Round to a decimal of your choosing:
round(1.3453,2)
#11
0
To handle rounding to any number of decimal places, a function with 2 lines of code will suffice for most needs. Here's some sample code to play with.
为了处理任意数量的小数,一个带有两行代码的函数将满足大多数需要。下面是一些示例代码。
var testNum = 134.9567654;
var decPl = 2;
var testRes = roundDec(testNum,decPl);
alert (testNum + ' rounded to ' + decPl + ' decimal places is ' + testRes);
function roundDec(nbr,dec_places){
var mult = Math.pow(10,dec_places);
return Math.round(nbr * mult) / mult;
}
#12
0
function discoverOriginalPrice(discountedPrice, salePercentage) {
var originalPrice = discountedPrice / (1 - (salePercentage * .01));
return +originalPrice.toFixed(2);
}
#13
-1
Here is a working example
这里有一个工作示例。
var value=200.2365455;
result=Math.round(value*100)/100 //result will be 200.24
#1
579
NOTE - See Edit 4 if 3 digit precision is important
注意-如果3位精度很重要,请参见编辑4。
var discount = (price / listprice).toFixed(2);
toFixed will round up or down for you depending on the values beyond 2 decimals.
根据两个小数点后的值,toFixed将会上下移动。
Example: http://jsfiddle.net/calder12/tv9HY/
例如:http://jsfiddle.net/calder12/tv9HY/
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
Edit - As mentioned by others this converts the result to a string. To avoid this:
编辑-正如其他人所提到的,它将结果转换为字符串。为了避免这种情况:
var discount = +((price / listprice).toFixed(2));
Edit 2- As also mentioned in the comments this function fails in some precision, in the case of 1.005 for example it will return 1.00 instead of 1.01. If accuracy to this degree is important I've found this answer: https://*.com/a/32605063/1726511 Which seems to work well with all the tests I've tried.
编辑2-正如在注释中提到的,这个函数在某些精度上失败了,例如在1.005的情况下,它将返回1.00而不是1.01。如果这个学位的精确度很重要,我已经找到了这个答案:https://*.com/a/32605063/1726511,它似乎与我尝试过的所有测试都很好。
There is one minor modification required though, the function in the answer linked above returns whole numbers when it rounds to one, so for example 99.004 will return 99 instead of 99.00 which isn't ideal for displaying prices.
虽然需要进行一个小的修改,但是在返回的结果中,这个函数会返回整数,因此,例如99.004将返回99,而不是99.00,这并不适合显示价格。
Edit 3 - Seems having the toFixed on the actual return was STILL screwing up some numbers, this final edit appears to work. Geez so many reworks!
编辑3 -似乎在实际的返回上固定了一些数字,这最后的编辑似乎起作用了。天啊这么多的重做!
var discount = roundTo((price / listprice), 2);
function roundTo(n, digits) {
if (digits === undefined) {
digits = 0;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
var test =(Math.round(n) / multiplicator);
return +(test.toFixed(digits));
}
See Fiddle example here: https://jsfiddle.net/calder12/3Lbhfy5s/
参见这里的小提琴示例:https://jsfiddle.net/calder12/3Lbhfy5s/。
Edit 4 - You guys are killing me. Edit 3 fails on negative numbers, without digging into why it's just easier to deal with turning a negative number positive before doing the rounding, then turning it back before returning the result.
编辑4 -你们杀了我。编辑3在负数上失败,没有深入探究为什么在做四舍两入之前,处理一个负数的正数更容易,然后在返回结果之前把它转回来。
function roundTo(n, digits) {
var negative = false;
if (digits === undefined) {
digits = 0;
}
if( n < 0) {
negative = true;
n = n * -1;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
n = (Math.round(n) / multiplicator).toFixed(2);
if( negative ) {
n = (n * -1).toFixed(2);
}
return n;
}
Fiddle: https://jsfiddle.net/3Lbhfy5s/79/
小提琴:https://jsfiddle.net/3Lbhfy5s/79/
#2
116
If you use a unary plus to convert a string to a number as documented on MDN.
如果使用unary plus将字符串转换为MDN上记录的数字。
For example:+discount.toFixed(2)
例如:+ discount.toFixed(2)
#3
34
The functions Math.round() and .toFixed() is meant to round to the nearest integer. You'll get incorrect results when dealing with decimals and using the "multiply and divide" method for Math.round() or parameter for .toFixed(). For example, if you try to round 1.005 using Math.round(1.005 * 100) / 100 then you'll get the result of 1, and 1.00 using .toFixed(2) instead of getting the correct answer of 1.01.
函数Math.round()和. tofixed()的意思是四舍五入到最接近的整数。使用Math.round()或参数for . tofixed()时,处理小数和使用“乘法和分隔”方法时,会得到不正确的结果。例如,如果您试图使用Math.round(1.005 * 100) / 100来尝试使用1.005,那么您将得到1和1.00使用. tofixed(2)的结果,而不是得到1.01的正确答案。
You can use following to solve this issue:
你可以用以下方法来解决这个问题:
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2');
Add .toFixed(2) to get the two decimal places you wanted.
加上。tofixed(2)得到你想要的两个小数点。
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2').toFixed(2);
You could make a function that will handle the rounding for you:
你可以做一个函数来处理你的四舍五入:
function round(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
Example: https://jsfiddle.net/k5tpq3pd/36/
例如:https://jsfiddle.net/k5tpq3pd/36/
Alternativ
Alternativ
You can add a round function to Number using prototype. I would not suggest adding .toFixed() here as it would return a string instead of number.
您可以使用原型添加一个圆形函数到数字。我不建议在这里添加. tofixed(),因为它将返回一个字符串而不是number。
Number.prototype.round = function(decimals) {
return Number((Math.round(this + "e" + decimals) + "e-" + decimals));
}
and use it like this:
然后像这样使用:
var numberToRound = 100 - (price / listprice) * 100;
numberToRound.round(2);
numberToRound.round(2).toFixed(2); //Converts it to string with two decimals
Example https://jsfiddle.net/k5tpq3pd/35/
比如https://jsfiddle.net/k5tpq3pd/35/
Source: http://www.jacklmoore.com/notes/rounding-in-javascript/
来源:http://www.jacklmoore.com/notes/rounding-in-javascript/
#4
27
To get the result with two decimals, you can do like this :
为了得到两个小数的结果,你可以这样做:
var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;
The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result.
取整数的值乘以100,保持前两个数字,然后除以100得到实际结果。
#5
13
try using discount.toFixed(2);
试着用discount.toFixed(2);
#6
7
A small variation on the accepted answer. toFixed(2)
returns a string, and you will always get two decimal places. These might be zeros. If you would like to suppress final zero(s), simply do this:
在接受的答案上有一个小的变化。toFixed(2)返回一个字符串,您将总是得到两个小数点。这些可能是零。如果你想要压制最后的零点,只要这样做:
var discount = + ((price / listprice).toFixed(2));
Edited: I've just discovered what seems to be a bug in Firefox 35.0.1, which means that the above may give NaN with some values.
I've changed my code to
编辑:我刚刚在Firefox 35.0.1中发现了一个bug,这意味着上面可能会给NaN一些值。我把代码改了。
var discount = Math.round(price / listprice * 100) / 100;
This gives a number with up to two decimal places. If you wanted three, you would multiply and divide by 1000, and so on.
The OP wants two decimal places always, but if toFixed() is broken in Firefox it needs fixing first.
See https://bugzilla.mozilla.org/show_bug.cgi?id=1134388
这给出了一个小数点后两位的数字。如果你想要三个,你可以乘上,除以1000,以此类推。OP总是需要两个小数点,但如果在Firefox中使用toFixed(),则需要先修复。参见https://bugzilla.mozilla.org/show_bug.cgi?id=1134388
#7
7
The best and simple solution I found is
我找到的最好和最简单的解决办法是。
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // 1.01
Reference: http://www.jacklmoore.com/notes/rounding-in-javascript/
参考:http://www.jacklmoore.com/notes/rounding-in-javascript/
#8
7
I think the best way I've seen it done is multiplying by 10 to the power of the number of digits, then doing a Math.round, then finally dividing by 10 to the power of digits. Here is a simple function I use in typescript:
我认为我看到的最好的方法是乘以10的数次方,然后做一个数学运算。圆,最后除以10的数次方。这是我在打字稿中使用的一个简单的函数:
function roundToXDigits(value: number, digits: number) {
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
Or plain javascript:
或纯javascript:
function roundToXDigits(value, digits) {
if(!digits){
digits = 2;
}
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
#9
5
Fastest Way - faster than toFixed():
最快的方式-比固定()更快:
TWO DECIMALS
x = .123456
result = Math.round(x * 100) / 100 // result .12
THREE DECIMALS
x = .123456
result = Math.round(x * 1000) / 1000 // result .123
#10
2
function round(num,dec)
{
num = Math.round(num+'e'+dec)
return Number(num+'e-'+dec)
}
//Round to a decimal of your choosing:
round(1.3453,2)
#11
0
To handle rounding to any number of decimal places, a function with 2 lines of code will suffice for most needs. Here's some sample code to play with.
为了处理任意数量的小数,一个带有两行代码的函数将满足大多数需要。下面是一些示例代码。
var testNum = 134.9567654;
var decPl = 2;
var testRes = roundDec(testNum,decPl);
alert (testNum + ' rounded to ' + decPl + ' decimal places is ' + testRes);
function roundDec(nbr,dec_places){
var mult = Math.pow(10,dec_places);
return Math.round(nbr * mult) / mult;
}
#12
0
function discoverOriginalPrice(discountedPrice, salePercentage) {
var originalPrice = discountedPrice / (1 - (salePercentage * .01));
return +originalPrice.toFixed(2);
}
#13
-1
Here is a working example
这里有一个工作示例。
var value=200.2365455;
result=Math.round(value*100)/100 //result will be 200.24