把金额截取(truncate)到角的函数.

来源:互联网 发布:pg美人网 淘宝 编辑:程序博客网 时间:2024/06/06 05:54

通过对double型金额先multiply 10转整型,再divide 10来truncate到是不正确的,因为,0.19999指的是0.20000而不是0.19,下面是为了解决这个问题写的代码段

// ConsoleApplication1.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <stdio.h>#include <iostream>using namespace std;/*把金额截取(truncate)到角的函数.Author:KagulaDate:2015-11-27Environment:VS2010SP1,VS2013Update5测试用例:51.19999返回51.2051.1999返回51.100返回0*/double degrade2tenth(double dbSrc){char buf[16];memset(buf, 0, sizeof(buf));//4是万分之一的误差,2是百分之一的误差.//vs2010没有round函数,可以用下面的方法来四舍五入.sprintf_s(buf, "%.4f", dbSrc);buf[strlen(buf) - 3] = '0';buf[strlen(buf) - 2] = '\0';return atof(buf);}int _tmain(int argc, _TCHAR* argv[]){{double dbSrc = 51.19999;cout << degrade2tenth(dbSrc) << endl;}{double dbSrc = 51.1999;cout << degrade2tenth(dbSrc) << endl;}{double dbSrc = 0;cout << degrade2tenth(dbSrc) << endl;}cin.get();return 0;}


0 0
原创粉丝点击