将浮动显示到文本框类型“数字"显示为“数字". [英] Displaying a Float to a Textbox type "number"

查看:73
本文介绍了将浮动显示到文本框类型“数字"显示为“数字".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于将文本框字符串转换为浮点值或允许类型为"number"的文本框允许使用小数点的问题很多,但是,我似乎找不到与显示将值浮动到文本框,其类型设置为数字".

到目前为止,我所拥有的是一个文本框,其类型为"number",而step ="0.01".最小值也为"0".它显示如下:

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

它可以很好地用于用户输入,并且可以毫无问题地将数据保存到变量/数据库中.但是,如果我想向用户显示相同的值,它什么也不会显示,甚至不会显示"0".

所以我的问题是:如何从浮点数"中获取值,将其转换为字符串",然后将其应用于Textbox.Text,以便显示值?

例如:如果我在文本框"中将值设置为"5",它将保存并显示"5",但是如果我输入"5.5"或"5,5",则无论哪种方式,它都不会显示,并且我需要显示"5.5".

有什么想法吗?

PS:应该代表货币价值.如果可能的话,我也希望有一个不需要Javascript的解决方案.

解决方案

浮点数5.5并不完全是5.5的真实值(请参见

使用此解决方案,您可以保持踩踏"0.01"的状态

P.S.正如Tiago所指出的,您的文化和浮点分隔符之间可能会出现不匹配的情况.小数点后有小数点,但您的数字可能有逗号.在这种情况下,请像这样进行转换:

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

从这个问题中得到它

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.

解决方案

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

这篇关于将浮动显示到文本框类型“数字"显示为“数字".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆