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

Number.toFixed() の代わりになる関数

Last updated at Posted at 2018-11-08

Number.toFixed vs getNumberDigit | CreateJS

小数点以下の桁数を指定して表示する Number.toFixed() の代わりになる関数
 例1:(0.005).toFixed(2) が 0.01 になる(正)
 例2:(-0.005).toFixed(2) が -0.01 になる(正)
 例3:(1.005).toFixed(2) が 1.00 になる(誤)
 例4:(-1.005).toFixed(2) が -1.00 になる(誤)
 例5:(2.005).toFixed(2) が 2.00 になる(誤)
 例6:(-2.005).toFixed(2) が -2.00 になる(誤)

////////////////////////////////////////
// 小数点以下の桁数表示(toFixedの代わり)
////////////////////////////////////////
function getNumberDigit(value, digit) {
	var shift = function(value, digit, reverse) {
		if (reverse) digit = -digit;
		var list = ("" + value).split("e");
		return Number(list[0] + "e" + (list[1] ? (Number(list[1]) + digit) : digit));
	};
	var sign = "";
	if (value < 0) {
		sign = "-";
		value = Math.abs(value);
	}
	var number = Math.round(shift(value, digit, false));
	return sign + shift(number, digit, true).toFixed(digit);
}
1
0
0

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?