你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?

我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。


当前回答

es6接受答案版本:

function round(value, precision) {
    const multiplier = 10 ** (precision || 0);
    return Math.round(value * multiplier) / multiplier;
}

其他回答

const solds = 136780000000; 
const number = (solds >= 1000000000 && solds < 1000000000000) ? { divisor: 1000000000, postfix: "B" }: (solds >= 1000000 && solds < 1000000000) ? { divisor: 1000000, postfix: "M" }: (solds >= 1000 && solds < 1000000) ? { divisor: 1000, postfix: "K" }: { divisor: 1, postfix: null }; 
const floor = Math.floor(solds / number.divisor).toLocaleString(); 
const firstDecimalIndex = solds.toLocaleString().charAt(floor.length+1); 
const final =firstDecimalIndex.match("0")? floor + number.postfix: floor + "." + firstDecimalIndex + number.postfix; 
console.log(final);

136780000000 --> 136.7B

1367800 --> 1.3M

1342 --> 1.3K

这似乎对我抛出的任何东西都有效:

function round(val, multiplesOf) {
  var s = 1 / multiplesOf;
  var res = Math.ceil(val*s)/s;
  res = res < val ? res + multiplesOf: res;
  var afterZero = multiplesOf.toString().split(".")[1];
  return parseFloat(res.toFixed(afterZero ? afterZero.length : 0));
}

它是四舍五入的,所以您可能需要根据用例修改它。这应该可以工作:

console.log(round(10.01, 1)); //outputs 11
console.log(round(10.01, 0.1)); //outputs 10.1

如果你的方法不起作用,请发布你的代码。

然而,你可以完成舍入任务如下:

var value = Math.round(234.567*100)/100

234.56英镑可以吗

类似的

 var value = Math.round(234.567*10)/10

会给出234.5

通过这种方式,您可以使用一个变量来代替前面使用的常量。

如果你关心正确的四舍五入,那么:

function roundNumericStrings(str , numOfDecPlacesRequired){ 
     var roundFactor = Math.pow(10, numOfDecPlacesRequired);  
     return (Math.round(parseFloat(str)*roundFactor)/roundFactor).toString();  }

否则,如果你没有,那么你已经从以前的帖子回复

str.slice(0, -1)

为什么不干脆

let myNumber = 213.27321;
+myNumber.toFixed(1); // => 213.3

toFixed: 返回使用定点表示法表示给定数字的字符串。 一元加号(+):一元加号运算符位于其操作数之前,求值为其操作数,但尝试将其转换为数字(如果它还不是数字)。