数値の文字列の整形をする関数を作成します。
JavaScriptで演算した結果を表示するとき、整数部の3桁ごとのカンマ区切りや、小数部の桁数を揃えたいときがあると思います。
そのようなときに役立つように、ライブラリ化しておくと便利でしょう。
function int3(num) {
var arr = new Array();
var str = "" + num;
if (str.search(/[^0-9]/) >= 0) return str;
for (i = 0;; i++) {
arr[i] = str.match(/[0-9]{3}$/);
if (!arr[i]) break;
str = str.replace(/[0-9]{3}$/, "");
}
for (j = i - 1; j >= 0; j--) {
if (str == "") str = arr[j];
else str = str + "," + arr[j];
}
return str;
}
//関数の実行:
document.write("int3(123456789) → ", int3(123456789));
document.write("<br>int3(12345) → ", int3(12345));
document.write("<br>int3(123) → ", int3(123));
document.write("<br>int3(12345.678) → ", int3(12345.678));
function round(num, n) {
var tmp = Math.pow(10, n);
return Math.round(num * tmp) / tmp;
}
//関数の実行
document.write("round(1.2345678, 3) → ", round(1.2345678, 3));
document.write("<br>round(1.2345678, 2) → ", round(1.2345678, 2));
document.write("<br>round(.12345678, 5) → ", round(.12345678, 5));
document.write("<br>round(1/3, 5) → ", round(1/3, 5));
document.write("<br>round(2/3, 5) → ", round(2/3, 5));
//関数の実行
document.write("round(12345678, -3) → ", round(12345678, -3));
document.write("<br>round(123456.78, -2) → ", round(123456.78, -2));
document.write("<br>round(1.2345678, -3) → ", round(1.2345678, -3));
document.write("<br>round(1234.5678, 0) → ", round(1234.5678, 0));
function roundx(num, n) {
var str = z = "";
str = "" + round(num, n);
if (n < 0) return str;
for (i = 0; i < n; i++) z = z + "0";
if (str.indexOf(".") < 0) return str + "." + z;
str = str + z;
return str.split(".")[0] + "." + str.split(".")[1].substring(0, n);
}
//関数の実行
document.write("roundx(1.2, 3) → ", roundx(1.2, 3));
document.write("<br>roundx(1234.56, 4) → ", roundx(1234.56, 4));
document.write("<br>roundx(1234.56789, 4) → ", roundx(1234.56789, 4));
//document.write("<br>roundx(123456789, 2) → ", roundx(123456789, 2));
document.write("<br>roundx(1234.56789, -2) → ", roundx(1234.56789, -2));
function roundz(num, n) {
var str = "";
str = roundx(num, n);
return int3(str.split(".")[0]) + "." + str.split(".")[1];
}
//関数の実行
document.write("roundz(1.2, 3) → ", roundz(1.2, 3));
document.write("<br>roundz(1234.56, 4) → ", roundz(1234.56, 4));
document.write("<br>roundz(1234.56789, 4) → ", roundz(1234.56789, 4));
document.write("<br>roundz(123456789, 2) → ", roundz(123456789, 2));
document.write("<br>roundz(1234.56789, -2) → ", roundz(1234.56789, -2));