这一行代码把数字四舍五入到小数点后两位。但我得到的数字是这样的:10.8、2.4等等。这些都不是我的小数点后两位的想法,所以我怎么能改善以下?
Math.round(price*Math.pow(10,2))/Math.pow(10,2);
我想要10.80、2.40等数字。jQuery的使用对我来说很好。
这一行代码把数字四舍五入到小数点后两位。但我得到的数字是这样的:10.8、2.4等等。这些都不是我的小数点后两位的想法,所以我怎么能改善以下?
Math.round(price*Math.pow(10,2))/Math.pow(10,2);
我想要10.80、2.40等数字。jQuery的使用对我来说很好。
当前回答
下面是https://stackoverflow.com/a/21323330/916734的TypeScript实现。它还使用了函数,并允许可选的数字偏移量。
export function round(rawValue: number | string, precision = 0, fractionDigitOffset = 0): number | string {
const value = Number(rawValue);
if (isNaN(value)) return rawValue;
precision = Number(precision);
if (precision % 1 !== 0) return NaN;
let [ stringValue, exponent ] = scientificNotationToParts(value);
let shiftExponent = exponentForPrecision(exponent, precision, Shift.Right);
const enlargedValue = toScientificNotation(stringValue, shiftExponent);
const roundedValue = Math.round(enlargedValue);
[ stringValue, exponent ] = scientificNotationToParts(roundedValue);
const precisionWithOffset = precision + fractionDigitOffset;
shiftExponent = exponentForPrecision(exponent, precisionWithOffset, Shift.Left);
return toScientificNotation(stringValue, shiftExponent);
}
enum Shift {
Left = -1,
Right = 1,
}
function scientificNotationToParts(value: number): Array<string> {
const [ stringValue, exponent ] = value.toString().split('e');
return [ stringValue, exponent ];
}
function exponentForPrecision(exponent: string, precision: number, shift: Shift): number {
precision = shift * precision;
return exponent ? (Number(exponent) + precision) : precision;
}
function toScientificNotation(value: string, exponent: number): number {
return Number(`${value}e${exponent}`);
}
其他回答
我不知道为什么我不能在之前的答案上添加评论(也许我是绝望的盲人,我不知道),但我用@Miguel的答案想出了一个解决方案:
function precise_round(num,decimals) {
return Math.round(num*Math.pow(10, decimals)) / Math.pow(10, decimals);
}
它的两条评论(来自@bighostkim和@Imre):
precise_round(1.275,2)不返回1.28的问题 precise_round(6,2)不返回6.00(正如他想要的)的问题。
我最终的解决方案如下:
function precise_round(num,decimals) {
var sign = num >= 0 ? 1 : -1;
return (Math.round((num*Math.pow(10,decimals)) + (sign*0.001)) / Math.pow(10,decimals)).toFixed(decimals);
}
正如你所看到的,我必须添加一点“更正”(这不是它是什么,但因为数学。round是有损的-你可以在jsfiddle.net上检查它-这是我知道如何“修复”它的唯一方法)。它在已经填充的数字上加了0.001,所以它在十进制值的右边加了一个1 3个0。所以使用起来应该是安全的。
之后,我添加了. tofixed(十进制),以始终以正确的格式输出数字(具有正确数量的小数)。
差不多就是这样了。好好使用它;)
编辑:增加了负数“更正”功能。
100%的工作! !试一试
<html> <head> <script> function replacePonto(){ var input = document.getElementById('qtd'); var ponto = input.value.split('.').length; var slash = input.value.split('-').length; if (ponto > 2) input.value=input.value.substr(0,(input.value.length)-1); if(slash > 2) input.value=input.value.substr(0,(input.value.length)-1); input.value=input.value.replace(/[^0-9.-]/,''); if (ponto ==2) input.value=input.value.substr(0,(input.value.indexOf('.')+3)); if(input.value == '.') input.value = ""; } </script> </head> <body> <input type="text" id="qtd" maxlength="10" style="width:140px" onkeyup="return replacePonto()"> </body> </html>
四舍五入您的十进制值,然后使用toFixed(x)为您期望的数字(s)。
function parseDecimalRoundAndFixed(num,dec){
var d = Math.pow(10,dec);
return (Math.round(num * d) / d).toFixed(dec);
}
Call
parseDecimalRoundAndFixed(10.800243929,4) => 10.80 parseDecimalRoundAndFixed(10.807243929,2) => 10.81
要使用定点表示法格式化一个数字,你可以简单地使用toFixed方法:
(10.8).toFixed(2); // "10.80"
var num = 2.4;
alert(num.toFixed(2)); // "2.40"
注意,toFixed()返回一个字符串。
注意:toFixed在90%的情况下不会四舍五入,它会返回四舍五入的值,但在很多情况下,它不起作用。
例如:
2.005.toFixed(2) === "2.00"
更新:
现在,你可以使用国际电话。NumberFormat构造函数。它是ECMAScript国际化API规范(ECMA402)的一部分。它有很好的浏览器支持,甚至包括IE11,并且Node.js完全支持它。
const formatter = new Intl。NumberFormat(“en - us”{ minimumFractionDigits: 2 maximumFractionDigits: 2 }); console.log (formatter.format (2.005));/ /“2.01” console.log (formatter.format (1.345));/ /“1.35”
你也可以使用toLocaleString方法,它会在内部使用Intl API:
const format = (num, decimals) => num. tolocalestring ('en-US', { minimumFractionDigits: 2 maximumFractionDigits: 2 }); console.log(格式(2.005));/ /“2.01” console.log(格式(1.345));/ /“1.35”
这个API还为您提供了各种格式选项,如千个分隔符、货币符号等。
将以下内容放在全局范围内:
Number.prototype.getDecimals = function ( decDigCount ) {
return this.toFixed(decDigCount);
}
然后试试:
var a = 56.23232323;
a.getDecimals(2); // will return 56.23
更新
请注意,toFixed()只能适用于0-20之间的小数,即a.g getdecimals(25)可能会生成一个javascript错误,所以为了适应,你可以添加一些额外的检查,即。
Number.prototype.getDecimals = function ( decDigCount ) {
return ( decDigCount > 20 ) ? this : this.toFixed(decDigCount);
}