Could someone please tell me how I could simplify this code?

In practice I have this code and it seems very tiring to do all those if there is a way to make it easier?
But that it works correctly? Because this code not only has * (multiplications) it also has 3 / (divisions).
If it only had multiplications it was easy to do it but it also has those divisons so it becomes more difficult to do so.
If anyone could help me thanks.

        function calculateLength() {
        
        
        
            var lengthinput = parseFloat(document.getElementById('lengthinput').value);


            var oper = document.getElementById('lengthselector1').value;
            var oper2 = document.getElementById('lengthselector2').value;


            if(oper === 'k' && oper2 === 'm')
            {
                document.getElementById('lengthresult').value = lengthinput*1000 || 0;
            }

            
            if(oper === 'k' && oper2 === 'd')
            {
                document.getElementById('lengthresult').value = lengthinput*10000 || 0;
            }

            if(oper === 'k' && oper2 === 'c')
            {
                document.getElementById('lengthresult').value = lengthinput*100000 || 0;
            }
            
            if(oper === 'k' && oper2 === 'mi')
            {
                document.getElementById('lengthresult').value = lengthinput*1000000 || 0;
            }

            if(oper === 'k' && oper2 === 'mic')
            {
                document.getElementById('lengthresult').value = lengthinput*1.0000E+9 || 0;
            }               
            
            if(oper === 'k' && oper2 === 'de')
            {
                document.getElementById('lengthresult').value = lengthinput*100 || 0;
            }

            if(oper === 'k' && oper2 === 'h')
            {
                document.getElementById('lengthresult').value = lengthinput*10 || 0;
            }   

            if(oper === 'k' && oper2 === 'me')
            {
                document.getElementById('lengthresult').value = lengthinput/1000 || 0;
            }
            
            if(oper === 'k' && oper2 === 'g')
            {
                document.getElementById('lengthresult').value = lengthinput/1000000 || 0;
            }

            if(oper === 'k' && oper2 === 'z')
            {
                document.getElementById('lengthresult').value = lengthinput/1.0000E+18 || 0;
            }               
            
            if(oper === 'k' && oper2 === 'i')
            {
                document.getElementById('lengthresult').value = lengthinput*39370.0787 || 0;
            }

            if(oper === 'k' && oper2 === 'a')
            {
                document.getElementById('lengthresult').value = lengthinput*1.0000E+13 || 0;
            }           
                            

        }

61 thoughts on “Could someone please tell me how I could simplify this code?”

Leave a Comment