function currencyValueFormatingRemoval(val) {
  return val.toString().replace(/,/g, '')
}

/**
 * Convert any number or string into currency value with thousand separator and decimal number
 * @param string String to convert for
 * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive
 * @returns string converted string
 */
export const getCurrencyValue = function(string, fractionDigits = 2) {
  if (typeof string !== 'undefined' && string !== null) {
    let toReplace = currencyValueFormatingRemoval(string)
    if (isNaN(parseFloat(toReplace))) {
      return string
    }
    return parseFloat(toReplace)
      .toFixed(fractionDigits)
      .toString()
      .replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,')
  }
  return string
}

/**
 * Convert a formatted number string to a parsed number
 *
 * @param string
 * @returns {number}
 */
export const getNumberValue = function(string) {
  if (string) {
    let toReplace = currencyValueFormatingRemoval(string)
    return parseFloat(toReplace)
  }
  return string
}

/** Note: below currency (decimal point) conversion max support until 13 CHAR long number ONLY
 * as it will cause DECIMAL_POINT_CONVERSION_ERROR by computer
 *
 * e.g. : 9.99999999999 * 100 will equals to 999.9999999990001
 *
 * e.g. : 9.999999999999999 *100 will equals to 999.9999999999998
 *
 * e.g. : 9.9999999999999999 *100 will equals to 1000
 *
 * @param string String to convert for
 * @param formatted to Apply extra currency formatting
 * @param fractionDigits Number of decimal to show after conversion
 * @returns string (converted) string
 */
export const convertToCurrencyAmount = function(string, formatted = true, fractionDigits = 2) {
  let value = currencyValueFormatingRemoval(string)

  if (value.length < 14) {
    value = (Math.floor(value * 100) / 100).toString()

    if (formatted) {
      value = getCurrencyValue(value, fractionDigits)
    }
  }
  return value
}
