Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force a string to 2 decimal places

Tags:

i have a repeater item that displays a double. occasionally the double seems to be coming out with 3 decimal places like this 1165.833. im trying to force it to two decimal places by wrapping it in a string.format method but it still comes out the same:

<%# String.Format("{0:f2}",DataBinder.Eval(Container.DataItem, "pricerange").ToString())%> 

any ideas why?

like image 326
phili Avatar asked Mar 02 '11 14:03

phili


People also ask

How do I format a string to two decimal places?

String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you round something to 2 decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

How do I format a string to two decimal places in Python?

In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.

How do you convert strings to decimals?

ToDecimal(String, IFormatProvider) Converts the specified string representation of a number to an equivalent decimal number, using the specified culture-specific formatting information.


2 Answers

String simply does not implement IFormattable. To use the formatting, remove .ToString() so that you aren't passing in a String.

<%# String.Format("{0:f2}",DataBinder.Eval(Container.DataItem, "pricerange"))%> 

To see this more explicitly, run this code:

Console.WriteLine(string.Format("{0:f2}", "123.888")); Console.WriteLine(string.Format("{0:f2}", 123.888)); 

which outputs

123.888 123.89 
like image 89
David Ruttka Avatar answered Sep 28 '22 05:09

David Ruttka


You can use:

String.Format("{0:0.00}",value); 
like image 37
Virtual Web Solutions Avatar answered Sep 28 '22 05:09

Virtual Web Solutions