How do you round to 1 decimal place in Javascript?

前端 未结 21 1437
难免孤独
难免孤独 2020-11-22 08:49

Can you round a number in javascript to 1 character after the decimal point (properly rounded)?

I tried the *10, round, /10 but it leaves two decimals at the end of

21条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 09:01

    Why not just

    let myNumber = 213.27321;
    +myNumber.toFixed(1); // => 213.3
    
    1. toFixed: returns a string representing the given number using fixed-point notation.
    2. Unary plus (+): The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.

提交回复
热议问题