So I have a form with a label which is supposed to display float value, the problem is that I need to have that number rounded to 2 decimal places whatever happens:
label1->Text = System::Convert::ToString( (float)((float)temperature/204.6) );
I tried looking for few hours but as I found there is no method for direct rounding of that beast equation and as far as I know no way to tell ToString() to round the thing to 2 decimals.
Is there any easy way to round the result to 2 decimal places inside ToString method?
这很简单:
String^ s = String::Format("{0:N2}", temperature/204.6);
Is there any easy way to round the result to 2 decimal places inside ToString method?
No, not with std::tostring()
and if you want to preserve trailing zeroes. Use a std::ostringstream
with appropriate I/O manipulators instead:
std::ostringstream oss;
oss << std::fixed << std::setprecision(2) << (temperature/204.6);
label1->Text = oss.str();
您不能将结果乘以100,转换为int,然后再除以100并转换为浮点数吗?
Here is JavaScript equivalent of toFixed:
#include <iostream>
std::string ToFixed(double number, size_t digits)
{
char format[10];
char str[64];
sprintf_s(format, "%%0.%zdf", digits);
return std::string(str, sprintf_s(str, format, number));
}
int main()
{
std::cout << ToFixed((double)12345 / 204.6, 2) << std::endl;
return 0;
}
Prints:
60.34
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.