Limit floating point precision?

2019-01-19 00:53发布

Is there a way to round floating points to 2 points? E.g.: 3576.7675745342556 becomes 3576.76.

9条回答
爷的心禁止访问
2楼-- · 2019-01-19 01:07

Don't use floats. Use integers storing the number of cents and print a decimal point before the last 2 places if you want to print dollars. Floats are almost always wrong for money unless you're doing simplistic calculations (like naive economic mathematical models) where only the magnitude of the numbers really matters and you never subtract nearby numbers.

查看更多
走好不送
3楼-- · 2019-01-19 01:09

Multiply by 100, round to integer (anyway you want), divide by 100. Note that since 1/100 cannot be represented precisely in floating point, consider keeping fixed-precision integers.

查看更多
劫难
4楼-- · 2019-01-19 01:10

For those of you googling to format a float to money like I was:

#include <iomanip>
#include <sstream>
#include <string>

std::string money_format (float val)
{
    std::ostringstream oss;

    oss << std::fixed << std::setfill ('0') << std::setprecision (2) << val;

    return oss.str();
}
// 12.3456 --> "12.35"
// 1.2 --> "1.20"

You must return it as a string. Putting it back into a float will lose the precision.

查看更多
放荡不羁爱自由
5楼-- · 2019-01-19 01:15

try use

std::cout<<std::setprecision(2)<<std::cout<<x;

should works and only 2 digit after the floating point appear.

查看更多
ゆ 、 Hurt°
6楼-- · 2019-01-19 01:16

Try this, it works perfectly

float=3576.7675745342556;
printf("%.2f",float);

change some objects in it to see and learn the code.

查看更多
三岁会撩人
7楼-- · 2019-01-19 01:18
yourFloatNumber= Float.Round(yourFloatNumber,2); // In C#
查看更多
登录 后发表回答