I have two doubles, 4.0 and 4.12345. I want to use ToString on them to receive just that, 4.0 and 4.12345, however the default ToString trims the 0 in 4.0 and if I try to use formats with F / N, I either have to pad or to round. Is there an easy generic solution I can use?
Thanks!
You can use the below format:
double number = 4.12345;
string s = number.ToString(".0####");
Which still maintains the '.0':
double number = 4.0;
string s = number.ToString(".0####");
You can add as many hashes as you want digits.
You can use the format below to convert double to string.
{0:0.00000}
More zeros can be added according to your need.
double myNumber = 4.12345;
var s = string.Format("{0:0.00000}", myNumber);
Console.WriteLine(s);
Updated code using ToString
double myNumber = 4.12345;
string s = myNumber.ToString("0.00000");
Console.WriteLine(s);
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.