1

I have a decimal value stored db as "12.3456" I want it to show it to client as "12.34"

I am using the code below .

<%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}")%>

I want the format to be like this

12.3456 --> 12.34

but it's giving me this instead.

12.3456 --> 12.3500

I am not sure if I am missing something or did something wrong.


UPDATE

I end up doing with asp:Label instead of <%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}")%>

Label Price.Text = Math.Truncate(12.3456* 100) / 100).ToString();

which gives me:

12.34

but if the number is 12.1000 it's giving me:

12.1

I need it in the 12.10 format

1
  • i need revers of this question , in model it's public decimal amount{get;set;} but when i enter value (29.0987) i get 30 or 0.1234 i get 0.12 but i need to have exact values it's possible Commented Dec 12, 2016 at 12:03

4 Answers 4

1

Use a format string of #.00 to always show to 2 decimal places.

Label price.Text = String.Format("{0:#.00}", 12.1000)

https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings

Sign up to request clarification or add additional context in comments.

5 Comments

this is also giving me 12.3500 i need 12.34
Are you sure, because Console.WriteLine("{0:#.00}", 12.3456); is displayed as 12.35. Are trying to round down, ie 12.34 instead of 12.35?
<%# DataBinder.Eval(Container.DataItem, "Price", "{0:#.00}")%> this is what i have in repeater right and i have 12.3456 in db. It's giving me 12.3500 on the page.
Something else must be modifying your output then. This is taken from above link on formatting. 0.45678 ("0.00", en-US) -> 0.46
Solved it by adding label control inside repeater Label price.Text = String.Format("{0:#.00}", 12.1000) --> 12,10
0

You can try like this:-

 <%# DataBinder.Eval(Container.DataItem, "Price", "{#.00}")%>

EDIT:-

I think you need the values without rounding it. You may try like this:-

var f = 12.3456;
f = Math.Truncate(f * 100) / 100;

4 Comments

This would round .3456 to .35
this is giving me 12.3500 i need 12.34
Since i am binding a list of items as they are in code behind. I would do a foreach loop as a last resort. I would like to solve this in <% %> tags because i have lots of pages like this so i could apply this easily in all of them.
i end up doing a foreach loop in the end
0

You can use

Math.Floor(12.3456*100) / 100 ;

Comments

0

.toString(C) 'C' is for Currency.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.