首页 > 解决方案 > 如何打印出 DECIMAL (tagDEC) 类型的值?

问题描述

我必须使用 DECIMAL 类型(tagDEC 结构)以获得更高的精度。

但是 Windows api 中 C++ 的 DECIMAL 只是一个结构。

typedef struct tagDEC {
    USHORT wReserved;
    union {
        struct {
            BYTE scale;
            BYTE sign;
        } DUMMYSTRUCTNAME;
        USHORT signscale;
    } DUMMYUNIONNAME;
    ULONG Hi32;
    union {
        struct {
            ULONG Lo32;
            ULONG Mid32;
        } DUMMYSTRUCTNAME2;
        ULONGLONG Lo64;
    } DUMMYUNIONNAME2;
} DECIMAL;

该值来自通过 tcp 套接字具有 .net DECIMAL 结构的对等点(C# 程序)。

那么如何以友好的方式显示/打印出它的值,例如 C++ 中的 - 12,345.678 * 10^(-21) ?

标签: c++windows

解决方案


使用一个简单的任意精度库(我发现这个,自由许可,仅标头),这应该是这样的:

DECIMAL input;
std::vector<Num::word> words{input.Lo64, input.Hi32};
Num n = Num(words.data(), words.data()+2, input.sign == 1).truncate() * Num(10).pow(input.scale);

std::vector<char> output;
n.print(output);
std::cout << output.data() << endl;

推荐阅读