2
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 5 years have passed since last update.

小数点以下X桁を指定して四捨五入

Last updated at Posted at 2017-05-30

自分用メモ。
Math.round()は整数になってしまうので、専用の関数が必要。
調べたらすぐ出てきますが、これはMathに組み込んでみる感じで作ってみた。
JavaScriptはオーバーロードできないので残念。

2017/05/31・2017/06/02追記
オーバーロードみたいなことが出来るようです。
standard-softwareさん、ありがとうございます。
もう既に自分の記事じゃなくなった感がハンパないですが(汗

/**
 * 小数点以下の桁数
 * @param {double} 数値
 * @param {integer} 小数点以下の桁数(省略可能)
 * @return {double} 四捨五入した値
 */
  Math.round = function (round_original) {
    return function (number, pricision) {
      var _pow;
      switch (arguments.length) {
      case 1:
        return round_original(number);
      case 2:
        _pow = Math.pow(10, pricision);
        return round_original(number * _pow) / _pow;
      }
    }
  }(Math.round);
2
0
5

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
2
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?