Sqlite:格式化整数

是否可以格式化整数列以使逗号作为Sqlite中的千位数分隔符?我想查询结果如下.

Id  Name      Price
1   Product1  1,000
2   Product2  2,500

最佳答案 SQLite中没有内置数字格式化功能,但您可以创建一个
user-defined function来创建一个.

这是一个有效的例子.使用整数,需要调整浮点数.

#import <sqlite3.h>
static char *sepnum(int num, char *buf, size_t buflen, char sepch)
{
    int len = 0, negative = 0;
    if (!buf || buflen == 0) return buf;
    if (num < 0)
    {
        negative = 1;
        num = abs(num);
    }
    for (int i=1;;i++)
    {
        if (buflen>len+1) buf[len++] = '0' + (num % 10);
        num /= 10;
        if (num==0) break;
        if ((i % 3) == 0 && buflen>len+1) buf[len++] = sepch;
    }
    if (negative && buflen>len+1) buf[len++] = '-';
    for (int i=0;i<len/2;i++)
    {
        buf[len] = buf[i];
        buf[i] = buf[len-i-1];
        buf[len-i-1] = buf[len];
    }
    if (buflen>len) buf[len] = '\0';
    else buf[0] = '\0';
    return buf;
}
static void nformat(sqlite3_context *context, int argc, sqlite3_value **argv)
{
   if (argc == 1) 
    {
        int num = sqlite3_value_int(argv[0]);
        char buf[500] = "";
        if (sepnum(num, buf, sizeof(buf), ','))
        {
            sqlite3_result_text(context, buf, -1, SQLITE_TRANSIENT);
            return;
        }
   }
  sqlite3_result_null(context);
}

int main(int argc, char *argv[]) 
{
    sqlite3 *db;
    sqlite3_open(":memory:", &db);
    sqlite3_stmt *stmt;
    sqlite3_create_function(db, "nformat", 1, SQLITE_UTF8, NULL, &nformat, NULL, NULL);
    sqlite3_prepare(db, "select nformat(1234)", -1, &stmt, NULL);
    sqlite3_step(stmt);
    printf("[%s]\n", sqlite3_column_text(stmt, 0));
}
点赞