프로그래밍/Js

ES6 부동소수점 계산 라이브러리

소행성왕자 2023. 3. 29. 15:53

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>