最小2桁の小数が必要ですか?
function toMinTwoDecimals(numString) {
var num = parseFloat(numString);
return num == num.toFixed(2) ? num.toFixed(2) : num.toString();
}
例:あなたの代わりにこれを使用し、そのまま2つ未満の小数と数字を残したい場合は
toMinTwoDecimals("1.0030"); // returns "1.003"
toMinTwoDecimals("1.0000"); // returns "1.00"
toMinTwoDecimals("1"); // returns "1.00"
toMinTwoDecimals("-5.24342234"); // returns "-5.24342234"
:
function toMinTwoDecimals(numString) {
var num = parseFloat(numString);
// Trim extra zeros for numbers with three or more
// significant decimals (e.g. "1.0030" => "1.003")
if (num != num.toFixed(2)) {
return num.toString();
}
// Leave numbers with zero or one decimal untouched
// (e.g. "5", "1.3")
if (numString === num.toFixed(0) || numString === num.toFixed(1)) {
return numString;
}
// Limit to two decimals for numbers with extra zeros
// (e.g. "1.0000" => "1.00", "1.1000000" => "1.10")
return num.toFixed(2);
}
あなたはするつもりはないここでは一つの方法です単なる丸め関数でそれを行うことができます。小数点以下桁数を検出するロジックが必要になり、適切な書式設定が適用されます。 –
@Dalorzoはポストを読んでいますが、私は数字を丸めたいとは思わない... –