js에서 0.1 + 0.2 를 하면 0.3이 나와야 하는데
0.30000000000000004
위와 같이 나온다.
이를 해결하기 위해 아래 라이브러리를 이용한다.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/9.0.0/decimal.min.js" integrity="sha512-zPQm8HS4Phjo9pUbbk+HPH3rSWu5H03NFvBpPf6D9EU2xasj0ZxhYAc/lvv/HVDWMSE1Autj19i6nZOfiVQbFQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src='https://cdn.jsdelivr.net/npm/bignumber.js@9.1.0/bignumber.min.js'></script> </head> <body> <script> const toFormat =(v,fixed)=>{ const tmp = new BigNumber(v); return tmp.toFormat(fixed); }; const add = (a,b)=>{ const t1 = new Decimal(a.replaceAll(',','')); const res = t1.add(b.replaceAll(',','')); return Number(res); }; const sub = (a,b)=>{ const t1 = new Decimal(a.replaceAll(',','')); const res = t1.sub(b.replaceAll(',','')); return Number(res); }; const mul = (a,b)=>{ const t1 = new Decimal(a.replaceAll(',','')); const res = t1.mul(b.replaceAll(',','')); return Number(res); }; const div = (a,b)=>{ const t1 = new Decimal(a.replaceAll(',','')); const res = t1.div(b.replaceAll(',','')); return Number(res); }; console.log('0.1+0.2 = ' + add('0.1', '0.2')); console.log('0.3-0.1 = ' + sub('0.3', '0.1')); console.log('1,243.09 * 1,500 = '+ toFormat( mul('1,243.09', '1,500'), 2) ); console.log('21.14 / 0.7 = '+ toFormat( div('21.14', '0.7'), 0) ); //let z = Decimal.add(0.1, 0.2); //z = Decimal.mul(1243.09, 1500); /* let y = new BigNumber('1234567.898765') let z = y.toFormat(4); let x = new BigNumber(0.1); let z = x.plus(0.2); */ </script> </body> </html>
'프로그래밍 > Js' 카테고리의 다른 글
ES6 클래스의 메소드를 함수호출하는 방법 (0) | 2023.03.31 |
---|---|
html table 을 엑셀로 출력하기 (0) | 2023.03.30 |
크롬 비활성화된 탭 네트워크(웹소켓) 끊어지는 현상 Intensive Wake Up Throttling (0) | 2023.03.07 |
안드로이드 웹뷰와 웹워커 브릿지 (android + webview + webworker bridge example) 샘플 (0) | 2023.02.28 |
방법2 WebRTC localhost Socket.io + Node.js 내부네트워크 정상 (1차완료) (0) | 2023.02.22 |