Click here to Skip to main content
15,666,033 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
I want to convert "67.56000" to double with 3 digits after decimal point and the value i want is 67.560 not 67.56.

Any suggestions. Is this Possible?

Limitation is that the type has to be double not decimal or string.

What I have tried:

I tried converting to get the desired value is string or decimal and converting back to double but still last 0s get removed.
I also tried Convert.ToDouble() with IFormatProvider..no luck with this also.
Posted
Updated 2-Dec-20 21:29pm

You cannot 'convert a string to a double with 3 digits after the decimal point'. You can just obtain a double from the input string. Then, you may format the double (string representation) according to your needs, e.g.

C#
string input = "67.56000";
double d = Double.Parse(input);
string rounded_input = string.Format("{0:f3}", d);
 
Share this answer
 
Comments
Member 14014388 3-Dec-20 4:11am    
final output has to be in double
CPallini 3-Dec-20 4:58am    
You cannot 'maintain trailing zeroes in a double'. Have a look at
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
Double values - and all numeric types in fact - do not store leading or trailing zeros, except when they are "important" to understanding the scale of a number. This is because numbers do not have any "format" associated with them.
For example, 000001 has no "zeros" to store, while 100000 does, because they are vital in order to store a representation of "one hundred thousand".
Similarly, trailing zeros after a decimal point are not stored because the number doesn't care is it is 1.2 or 1.2000000000 - there is no difference between the two values.

You only get leading or trailing zeros when you convert a value to a string for presentation to a user, and that means using either using Tostring or a string format specifier:
C#
double d = 67.56;
Console.WriteLine(d.ToString("0.000"));
Console.WriteLine("{0:0.000}", d);
Console.WriteLine($"{d:0.000}");
Will all print "67.560"
 
Share this answer
 
Comments
Member 14014388 3-Dec-20 4:13am    
yeah... thanks for the clarification. I was also thinking the same.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900