Represent the fraction of two numbers in the string format | Function to return the required fraction in string format ; If the numerator is zero , answer is 0 ; If any one ( out of numerator and denominator ) is - ve , sign of resultant answer - ve . ; Calculate the absolute part ( before decimal point ) . ; Output string to store the answer ; Append sign ; Append the initial part ; If completely divisible , return answer . ; Initialize Remainder ; Position at which fraction starts repeating if it exists ; If this remainder is already seen , then there exists a repeating fraction . ; Index to insert parentheses ; Calculate quotient , append it to result and calculate next remainder ; If repeating fraction exists , insert parentheses . ; Return result . ; Drivers Code
function calculateFraction ( num , den ) { if ( num == 0 ) return " " ; var sign = ( num < 0 ) ^ ( den < 0 ) ? - 1 : 1 ; num = Math . abs ( num ) ; den = Math . abs ( den ) ; var initial = parseInt ( num / den ) ; var res = [ ] ; if ( sign == - 1 ) res . push ( " " ) ; res . push ( initial . toString ( ) ) ; if ( num % den == 0 ) return res ; res . push ( " " ) ; var rem = num % den ; var mp = new Map ( ) ; var index ; var repeating = false ; while ( rem > 0 && ! repeating ) { if ( mp . has ( rem ) ) { index = mp . get ( rem ) ; repeating = true ; break ; } else mp . set ( rem , res . length ) ; rem = rem * 10 ; var temp = parseInt ( rem / den ) ; res . push ( temp . toString ( ) ) ; rem = rem % den ; } if ( repeating ) { res . push ( " " ) ; res . splice ( index , 0 , " " ) ; } return res . join ( ' ' ) ; } var num = 50 , den = 22 ; document . write ( calculateFraction ( num , den ) + " " ) ; num = - 1 , den = 2 ; document . write ( calculateFraction ( num , den ) ) ;