Skip to content

Instantly share code, notes, and snippets.

@blippy
Last active March 22, 2017 18:42
Show Gist options
  • Select an option

  • Save blippy/139fb0f2dff8703b6eae8129509d0d14 to your computer and use it in GitHub Desktop.

Select an option

Save blippy/139fb0f2dff8703b6eae8129509d0d14 to your computer and use it in GitHub Desktop.
Decimal arithmetic C and C++ interoperability
#pragma once
#ifdef __cplusplus
#include <decimal/decimal>
typedef std::decimal::decimal64::__decfloat64 Num;
#else
typedef _Decimal64 Num;
#endif
#ifdef __cplusplus
extern "C" {
#endif
Num get_num();
void print_num(Num n);
#ifdef __cplusplus
}
#endif
#include "dec.h"
Num get_num()
{
return 0.2DD;
}
#include <decimal/decimal>
#include <iostream>
#include <iomanip> // for std::setprecision()
#include "dec.h"
void print_num(Num n)
{
std::decimal::decimal64 d64(n);
std::cout << std::setprecision(20) << std::decimal::decimal_to_float(d64) << std::endl;
// Output is 0.20000000298023223877
}
int main()
{
Num n = get_num();
print_num(n);
std::cout << ( 0.1 + 0.2 == 0.3) << std::endl; // false (0)
std::cout << ( 0.1DD + 0.2DD == 0.3DD) << std::endl; // true (1)
return 0;
}
dec : decc.o deccc.o
g++ decc.o deccc.o -o dec
decc.o : decc.c
gcc -c decc.c
deccc.o : deccc.cc
g++ -c deccc.cc
.PHONY : clean
clean :
rm -f *.o dec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment