1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Typescript/Javascript] 特定の小数点位置で四捨五入する方法

Posted at

javascriptの標準関数が整数にするための四捨五入しかなかったので拡張してみました

結論

function roundDecimal(value: number, decimalPoint: number) {
    const x = 1 / decimalPoint
    return Math.round(value * x) / x
}

解説

少数第二位までを四捨五入して表示したい場合
1 / 0.01とするとxに100が入る
valueに100をかけることで少数点第二位までが整数となり、小数点第三位が小数点第一位となることでMath.roundで四捨五入することができる
そのあと、かけた100で割ってあげることでふたたびもとの値に戻すことができる

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?