최소 두 자리수를 원하십니까?
function toMinTwoDecimals(numString) {
var num = parseFloat(numString);
return num == num.toFixed(2) ? num.toFixed(2) : num.toString();
}
예 :
당신 미만이 개 소수의 손길이 닿지 않은으로 번호를 마칠 경우
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가 게시물을 읽었습니다. 숫자를 반올림하고 싶지 않습니다 ... –