Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a Float to a Textbox type "number"

There is a lot of questions regarding the conversion of a Textbox string to a float value, or allowing a Textbox of type="number" to allow decimal points, however, I can't seem to find anything related to displaying a float value to a Textbox with it's type set to "number".

So far, what I have is a Textbox with type="number" and step="0.01". It also has a min value of "0". It shows like this:

<asp:TextBox ID="TextBox1" runat="server" TextMode="Number" step="0.01" Width="140px" min="0"></asp:TextBox>

It works fine for user input and saves the data to a varable/database without any problem. However, if I want to display this same value back to the user, it doesn't display anything, not even a "0".

So my question is: How can I take the value form a "float", convert it to a "string", and apply it to the Textbox.Text, so that it displays the value?

As an example: If I set the value in the Textbox as "5", it will save and display "5", but if I put "5.5" or "5,5", either way, it never displays it, and I need it to display "5.5".

Any ideas?

PS: It is supposed to represent a monetary value. I would also prefer to have a solution that doesn't require Javascript, if possible.

like image 439
Tiago Cachinho Avatar asked Jun 30 '15 11:06

Tiago Cachinho


2 Answers

set any value to step attribute.

 <input type="number" step="any"/>

You can use Convert.ToSingle() or float.Parse to convert string to float

var value = Convert.ToSingle(TextBox1.Text, CultureInfo.InvariantCulture);
 //Or
 var value1 = float.Parse(TextBox1.Text, CultureInfo.InvariantCulture);

And use ToString("N") of instance method to convert float to string.

var str = floatNum.ToString("N"); // or N2 (2 digit decimal)
like image 153
KV Prajapati Avatar answered Sep 25 '22 07:09

KV Prajapati


A float 5.5 is not exactly a real value of 5.5 (see .Net Float Reference)

I strongly suggest you to NEVER use floats for monetary values! It is best practice to use a decimal type for These things.

That said, if you really want to use floats, when you read the value from the DB do this:

TextBox1.Text = ((decimal)myNum.ToString( "0.##" )).Tostring()

With this solution you can leave the stepping as you whish "0.01"

P.S. As Tiago pointed out there can be a mismatch between your culture and the floating point separator. decimals expect dots but maybe your number has a comma. In this case convert like that:

decimal.Parse("18,285", new NumberFormatInfo() { NumberDecimalSeparator = "," })

got it from this question

like image 42
KarmaEDV Avatar answered Sep 23 '22 07:09

KarmaEDV