免费跨平台库将数字(金额)转换为单词?

bia*_*lix 9 c c++ free cross-platform

我正在寻找可以在我的C应用程序中使用的跨平台库来将金额(例如$ 123.50)兑换成单词(一百二十三美元和五十美分).我需要支持多种货币:美元,欧元,英镑等.

虽然我明白编写自己的实现并不难,但我想避免重新发明轮子.我试图谷歌它,但有太多的噪音与MS Word转换器有关.

任何人都可以提出建议吗?

更新许多评论建议编写我自己的实现,因为它真的很容易.并且我同意.我的观点是在同一时间支持多种货币和不同的业务规则来拼写金额(应该是小部分写成文本或数字?等等)据我所知,严肃的商业应用程序里面有这样的库,但我认为有没有任何开源可用,也许是因为它看起来非常容易.

我将编写自己的库,然后开源.谢谢大家.

Cod*_*odo 1

您在寻找这样的东西吗?这不是一个完整的解决方案,因为它将货币的处理外部化。此外,对于负数它会失败。

只需分配一个字符缓冲区并调用write_number. 第三和第四个参数预计是货币单位(复数形式),例如“dollars”和“cents”。(个别情况尚未妥善处理。

#include <math.h>
#include <string.h>

const char* SMALL_NUMBERS[] = {
    0, "one ", "two ", "three ", "four ",
    "five ", "six ", "seven ", "eight ", "nine ",
    "ten ", "eleven ", "twelve ", "thirteen ", "fourteen ",
    "fiftenn ", "sixteen ", "seventeen ", "eighteen ", "nineteen "
};

const char* TENS[] = {
    0, 0, "twenty ", "thirty ", "forty ",
    "fifty ", "sixty ", "seventy ", "eighty ", "ninety "
};


void append_lt_1000(char* buf, int num)
{
    if (num >= 100) {
        strcat(buf, SMALL_NUMBERS[num / 100]);
        strcat(buf, "hundred ");
        num %= 100;
    }
    if (num >= 20) {
        strcat(buf, TENS[num / 10]);
        num %= 10;
    }
    if (num != 0)
        strcat(buf, SMALL_NUMBERS[num]);
}

void append_mag(char* buf, double* number, double magnitude, const char* mag_name)
{
    if (*number < magnitude)
        return;

    append_lt_1000(buf, (int)(*number / magnitude));
    strcat(buf, mag_name);
    *number = fmod(*number, magnitude);
}

void write_number(char* buf, double number, const char* major_unit, const char* minor_unit)
{
    double ip, fp;

    buf[0] = 0;
    fp = modf(number, &ip);

    if (ip == 0) {
        strcat(buf, "zero ");
    } else {
        append_mag(buf, &ip, 1000000000000.0, "trillion ");
        append_mag(buf, &ip, 1000000000.0, "billion ");
        append_mag(buf, &ip, 1000000, "million ");
        append_mag(buf, &ip, 1000, "thousand ");
        append_lt_1000(buf, (int)ip);
    }
    strcat(buf, major_unit);

    if (fp != 0) {
        strcat(buf, " and ");
        append_lt_1000(buf, (int)(fp * 100));
        strcat(buf, minor_unit);
    }
}
Run Code Online (Sandbox Code Playgroud)