Skip to content

Currency to Words

A variant of the NumberToWords would be a CurrencyToWords. The following 'C' code needs to be added to the functions DLL code:

std::string CurrencyToWords(double nNumberToConvert, int iNumberOfDecimals)
{
    int FirstPart = (int)nNumberToConvert;
    int SecondPart = std::round((nNumberToConvert - FirstPart) * pow(10, iNumberOfDecimals));
    if (SecondPart < 0)
        SecondPart = SecondPart * -1;
    std::string sWordsPart1 = IntegerToWords(FirstPart);
    std::string sWordsPart2 = SmallNumberToWords(SecondPart, "");
    if ((iNumberOfDecimals > 0) && sWordsPart2.length() > 0)
    {
        return sWordsPart1 + " Dollars and " + sWordsPart2 + " Cents";
    }
    else
    {
        return sWordsPart1 + " Dollars and No Cents";
    }
}

VARIANT __declspec(dllexport) currency2words(VARIANT vNumberToConvert, VARIANT vDecimalPositions)
{
    CComVariant vRes, vNum, vPos;

    std::string sWords;

    USES_CONVERSION;

    vNum = vNumberToConvert;
    vPos = vDecimalPositions;

    // Convert data to bigint
    vNum.ChangeType(VT_R8, NULL);

    // Convert data to integer
    vPos.ChangeType(VT_I4, NULL);

    // Check argument types
    if (vNum.vt != VT_R8) // VT_R8 = double
    {
        vRes.vt = VT_ERROR;
        vRes.scode = MAKE_HRESULT(1, FACILITY_ITF, IDS_PARAM1_NO_DOUBLE);
        return vRes;
    }

    if (vPos.vt != VT_I4) // VT_I4 = 4 byte signed int
    {
        vRes.vt = VT_ERROR;
        vRes.scode = MAKE_HRESULT(1, FACILITY_ITF, IDS_PARAM2_NO_INTEGER);
        return vRes;
    }

    sWords = CurrencyToWords(vNum.dblVal, vPos.intVal);
    // Return the words
    vRes = sWords.c_str();
    return vRes;
}