How to convert a double
into a string
with 6 max number of digits and remove trailing zeros?
I want to have :
2.123456123 -> "2.123456"
0.0000012 -> "0.000001" (and not "1.2e-6")
12.45 -> "12.45" (and not "12.450000")
36 -> "36" (and not "36.000000")
using string.Format("{0:F6"}, value)
output trailing zeros and string.Format("{0:G6"}, value)
will not fit the second example.
Is it ok to use value.ToString("0.######)
?
Is there an equivalent way to do with string.Format()
?
It is okay to use value.ToString("0.######")
. However, you should consider another thing: double
is not a decimal (base 10) number. You should not rely on the decimal representation of the number to be anything reasonable - plenty of normal decimal base 10 numbers require infinite decimal expansion in base 2.
If you do care about the decimal representation, it might be a better idea to use decimal
instead - it's also a floating point number, but in base 10.
And in either case, this involves rounding - that might or might not be what you want.
tokens is a ViewModel with Price string property:
foreach (var item in tokens)
{
item.Price = double.Parse(item.Price).ToString("#,0");
}
// 123456 => 123,456
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.