C ++中的分数和百分比的财务公式 [英] Financial formulas with cents and percentages in C++

查看:172
本文介绍了C ++中的分数和百分比的财务公式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小公式适用于金额,我使用美分(金钱大约100分)对我的钱对象,以确保浮动不乱。但是,我不知道如何应用百分比计算使用。例如,以下的利率公式:$ 500 * 0,0048%* 5(500美元,在0,0048%/天,在5天内)



如何在计算期间正确地表示百分比?要使用

://en.wikipedia.org/wiki/Fixed-point_arithmeticrel =nofollow> fixed point arithmetics



当你说你是存储分,你其实说你的数字都乘以100 - 这是你不存储的另一条信息。所以0.01 $表示为1/100。 0,0048可以表示为48/10000并且计算变为:

  50000/100 * 48/10000 * 5 = 12000000/1000000 = 1200/100 

比您转换回分(重要:您检查溢出,缺少位)以规范化您的首选表示

注意,这也是微控制器(没有fpu,低性能)使用的典型方法



或者,如果你不关心性能,你也可以使用任意精度算术库,如 GMP


I have a small formula to apply to a money amount and i'm using cents (dividing the money about by 100) on my Money objects to make sure floats are not messing things up. However, i'm not sure how to apply a percentage calculation using that. For example, an interest rate formula of the following: $500 * 0,0048% * 5 (500 bucks, at 0,0048%/day, during 5 days)

How do i represent the percentage properly during my calculation? Would it have to be 50000 * 0.000048f * 5?

解决方案

you need to evaluate your operations using fixed point arithmetics.

When you state that you are storing cents, you are in fact saying that your numbers have been all multiplied by 100 - that's another piece of information you are not storing. So 0.01$ is represented as 1/100. 0,0048 can be represented then as 48/10000 and the computation become:

50000/100 * 48/10000 * 5 = 12000000/1000000 = 1200/100

than you convert back to cents (IMPORTANT: at every step it's mandatory you check for overflows, missing bits) to normalize to your preferred representations

Note that this is also the typical approach used with micro-controllers (no fpu, low performance)

As an alternative, if you don't care much about performance you can also make use of arbitrary precision arithmetic libraries, as GMP.

这篇关于C ++中的分数和百分比的财务公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆