C++ decimal output formatting

寵の児 提交于 2020-01-04 15:28:59

问题


i'm writing a double value to a file. The numeric value is written with a point as a decimal separator. I would like to use a comma. How i can do that?


回答1:


The usual way is to use a locale with the decimal separator set to the comma. If your machine is configured for that generally, you can probably just use the nameless locale for it:

std::cout.imbue(std::locale(""));
std::cout << 12345.67;



回答2:


You can find the answer in an earlier question This basically changes the locale used by the streams you are using.




回答3:


I think in the library cmath

there is a function called modf which takes a float or double, and a pointer to an float or double, and returns an integer.

double intPart;
double fractPart;
fractPart = modf(doubleValue, &intPart);

So you pass in the double value, it returns the decimal part as an integer, and the integer value is stored in the pointer you passed in.

You could then write these to file however you want, with a comma in the middle or whatever, just write it as two separate numbers. float or double



来源:https://stackoverflow.com/questions/2226045/c-decimal-output-formatting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!