How to make a Currency class from std.BigInt?

RuZzz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 30 12:25:30 PST 2015


module axfinance.api.currencies;

import std.array, std.stdio, std.system, std.bigint, std.conv;


class Currencies
{
	public:
		this(ulong pf)
		{
			exponent(pf);
		}
		bool integer(BigInt pb)
		{
			zInt = pb;
			return true;
		}
		string value()
		{
			string res = to!string(zInt);
			insertInPlace(res, res.length - zExp,".");
			return res;
		}
	private:
		bool exponent(ulong pe)
		{
			zExp = pe;
			return true;
		}
		BigInt zInt;
		ulong zExp;
}

unittest
{
	double d1 = 45.67;
	immutable LIM_FIAT = 2, LIM_EXCH = 6, LIM_CRYP = 8;
	auto c = [	"BTC":["N-01":new Currencies(LIM_CRYP), "N-02":new 
Currencies(LIM_CRYP), "SUM1":new Currencies(LIM_CRYP)],
			"CNY":["N-01":new Currencies(LIM_FIAT), "N-02":new 
Currencies(LIM_EXCH), "N-03":new Currencies(LIM_CRYP), "SUM1":new 
Currencies(LIM_CRYP), "SUM2":new Currencies(LIM_CRYP)]];
//	 EUR, LTC, RUB;

	c["BTC"]["N-01"] = 1.00000002;//Error: cannot implicitly convert 
expression (1) of type double to 
axfinance.api.currencies.Currencies
	c["BTC"]["N-02"] = 15.00000002+"13455565.45665435";
	c["BTC"]["SUM1"] = c["BTC"]["N-01"] + c["BTC"]["N-02"];
	assert(c["BTC"]["SUM1"] == "13455581.45665437");
	c["CNY"]["N-01"] = 1.02;
	c["CNY"]["N-02"] = "0.01";
	c["CNY"]["N-03"] = "0.00000001";
	c["CNY"]["SUM1"] = c["CNY"]["N-01"] + c["CNY"]["N-02"];
	assert(c["CNY"]["SUM1"] == "1.03");
	assert(to!double(c["CNY"]["SUM1"]) == 1.03);
	c["CNY"]["SUM2"] = c["CNY"]["N-01"] + c["CNY"]["N-03"];
	assert(c["CNY"]["SUM2"] == "1.02000001");
}


More information about the Digitalmars-d-learn mailing list