var select = document.getElementById('input-select');
// 셀렉트 추가
for (var i = -15; i <= 15; i+=0.01) {
var option = document.createElement("option");
option.text = i;
option.value = i;
select.appendChild(option);
}

자바스크립트 for 문으로 0.01단위로 증가해서 옵션 넣을려고하는데 -14.96이후에 자리수가 망가져서 나오고있습니다..
무엇이 문제가 있는지 알려주시면 감사하겠습니다
|
답변 1개 / 댓글 3개
채택된 답변
+20 포인트
2020-03-12 (목) 12:23:51
자리수 문제는 컴퓨터의 고질적인 문제죠 ^^
그냥 아래처럼 처리하면 됩니다
Copy
var select = document.getElementById('input-select');
// 셀렉트 추가
for (var i = -15; i <= 15; i+=0.01) {
var option = document.createElement("option");
var num = i.toFixed(2); // 소수점 두자리 까지 고정
option.text = num;
option.value = num;
select.appendChild(option);
}
답변에 대한 댓글 3개
백수1995
2020-03-12 (목) 13:40:08
그럴리가요.. 그다음에
option.text = num;
option.value = num;
이것도 바꾸셨나요?
option.text = num;
option.value = num;
이것도 바꾸셨나요?
2020-03-12 (목) 13:54:00
아 그부분을 따로 수정을 안했었네요 ;; 적용하니 소수점2개까지 잘 되었습니다. 감사합니다.
답변을 작성하려면 로그인이 필요합니다.