Is it possible say a person enters an integer value 5 in a Textbox and automaticall a .00 is added in the end say 5.00
<asp:TextBox ID="txtAmountTransfer" runat="server" Width="55%" CssClass="right"></asp:TextBox>
You can use .toFixed(2) which will add the zero's
see this for an example js Fiddle
#CR41G14 is correct. .toFixed(2) is all you need.
As far as where and how, I would recommend using the change event on the input box as it is the least intrusive for the user. (The blur event would also not be unreasonable)
Since the value of the text field will be a string you will need to parse it as #Snuffleupagus points out. In your case, I would recommend parseFloat because then your field could potentially handle the user entering 5.2 which could become 5.20. (using parseInt you would end up with 5.00).
One additional note is recognizing that if the user types non-numeric characters (or really any value that will not parse) into the field, it will result in a display of NaN, which actually seems fairly reasonable in your case.
Using jQuery:
$('#txtAmountTransfer').change(function(){
$(this).val(parseFloat($(this).val()).toFixed(2))
});
Similar example using native code:
var textField = document.getElementById('txtAmountTransfer');
textField.onchange = function(){
this.value = parseFloat(this.value).toFixed(2);
}
Related
I'm using an Infragistics UltraGrid and I have a table where the first column is a Double field, I use a dll NCalc.Expression so the user can input a formula and get a double value, of course only if it is a valid formula. The problem is on method beforeCellUpdate, I can't change the value to the value generated by the evaluate method from NCalc.Expression. I tried to store the new value as a class variable and then update the value at afterCellUpdate method but then I get a Data Error - data error due to formula being not a double but a string, input not valid
What does this mean? And how can it be fixed?
After all night I use the method berofeExitEditMode, that way I evaluate the input formula, if its not valid cancel the event, if the formula its correct, then change the value for the generated value.
It worked so far.
IF anyone knows a better way it would be much appreciated
You may check this article where is shown how you can validate the user's input "Validate User Input"
So I'm trying to use the RangeValidator to ensure the minimum and maximum value of Int64 is validated. But, the only or closest option that I seem to have is Double.
Dim Range As New RangeValidator
Range.ControlToValidate = "..."
Range.Type = ValidationDataType.Double
Range.MinValue = Int64.MinValue.ToString
Range.MaxValue = Int64.MaxValue.ToString
I don't want to use a custom validator. I suppose I could use some crazy regular expression.. but just trying to understand why I can't do this.
For example, the max value of Int64 is:
9223372036854775807
But this validates:
9223372036854775808
9223372036854775810
9223372036854775899
It will not validate if I jump up a larger number:
9223372036854799999
I'm assuming it's due to some conversion taking place for a Double.
I do see there's a LongValidator in System.Configuration, but I'm trying to avoid creating a CustomValidator type if at all possible and it's a different validate type, as in not intended for use like RangeValidator.
All of this is more so for learning purposes than anything else. I'm aware I can jump through other hoops but hoping to get better clarity.
Tagged C# as well. Ignore my vb.net example.. not really important based on the question. Will convert any code either way.
I found a plausible answer on a forum by PLBlum
I want to clarify something. RangeValidator does not use a
regularexpression to validate a double. It uses a regular expression
to extract the digits and decimal character out of the string. It then
converts the result into an actual number using the javascript
parseFloat() function. If that function cannot convert, the
RangeValidator knows the value was not acceptable to javascript.
I suspect that the problem is that the value you are assigning to
MaximumValue is too large for javascript's floating point. I think
both .net's Double and javascript are 80bit floating point but its
possible they are slightly different at the min and max range. In any
case, I recommend changing your code like this:
Use a CompareValidator, Operator=DataTypeCheck, Type=Double. It will report an illegal value due to the format or its too big for an 80 bit
number.
Use another CompareValidator, Operator=GreaterThanEqual, Type=Double, ValueToCompare= your minimum double. This will report an
error if anything is below the minimum. The max was handled in the
other validator.
Maybe that explains why it is validating incorrectly.
Unless someone else wants to chime in, realistically there's one way I found to do this, and that's with a custom validator. There's a function in System.configuration that allows the ability to check if a value is a valid "Long". The problem is, if you want client-side validation it seems the only valid option is to use a regex. Otherwise, the number is just too big and JavaScript parses it as a float, as Sam mentioned.
So, I ended up using a regex as to gain client-side and server-side validation.
I'm learning how to write custom workflows and am trying to figure out where and in which format all the values I need are stored. I have noticed that I can access Entity instance data in both the Attributes and FormattedValues properties. How do I know when to use which one?
I have noticed MSDN's remark "Entity formatted values are only available on a retrieve operation, not on an update operation.".
For testing I've made two foreach-blocks iterating through both collections. Attributes gives me 65 lines and FormattedValues gives me 39. I can see that, yes, the output from FormattedValues is indeed formatted.
For example, where Attributes gives the output "Microsoft.Xrm.Sdk.OptionSetValue", FormattedValues gives me a string with the actual value.
Which values/attributes are generally excluded from the FormattedValues collection and why?
I'm not 100% sure about this, but the formatted values are the values you will be able to see on the form. In that list you will be able to find money types with the $ symbol, or the labels of the option sets. A text field shouldn't be shown since is already human-readable.
https://community.dynamics.com/crm/b/crmmitchmilam/archive/2013/04/18/crm-sdk-nugget-entity-formattedvalues-property.aspx
Refer to this article to know a little bit more about it. I rareley using that attribute list since the data is in string format. I found it really useful to retrieve the OprionSet lables.
After a quick check it'd appear that the difference between an attribute and a formatted value is that the former to the actual value stored in the DB (or at least the value that was stored there at the occasion of fetching it) while the latter serves what's shown to the user.
I haven't used formatted values but until proven otherwise, I'd say that an entity's attribute will provide you with the typed value that the regarded field is based on (be that int, DateTime and such), whereas its formatted value is the rendered, stringified representation of that value (being dependent on e.g. what form you're referring to, what language etc.)
By that logic, I'd expect the set of formatted values to be a subset to the set of attributes. Also, it should be constituted of exclusively String typed values, while the counterpart is a member of the type conversion table.
An example of the difference I can think of is an option set called picky with the currently selected option named "hazaa" and the ID of 1234. The below sample is written by heart so feel free to correct. It exemplifies the point, though: plainValue will be an integer equal to 1234, while formattedValue will be "hazaa".
int plainValue = (int)entity["picky"];
String formattedValue = (String)entity.FormattedValues["picky"];
I'd say that the attributive approach is more reliable as it'll render the actual values, while the alternative can lead to unexpected outcome. However, there's a certain convenience to it, I must add.
Personally, I'd recommend to look into the method GetAttributeValue<T>(String) or, as every cocky CRM developer would - have your own class with extension methods and use the method Get<T>(T,String) in there. That provides you with the sense of control and offers the best predictability and readability, IMAO.
well in my database i had a colum for price of one product
i had it as float, my problem is if i saved it since my c# application
as 10.50 .. in a query it returns 10,50 and if i update i get a error
10,50 cant convert to float ... or something so..
and if i saved it as decimal, in queries inside sql management .. are ok..
but in my c# application... i get the same error..
10.50 retuns as 10,50 i dont know why, and how to solved it.. my unique solution is saved it
as varchar...
That's a localisation problem of some sort. 10,50 is the "European" way of writing ten and a half. If you're getting that from your select statements then your database is probably configured incorrectly.
Generally speaking you should use the same type throughout your layers. So if the underlying types in the database are x, you should pass around those data with identical types in c#, too.
What type you choose depends on what you are storing--you shouldn't be switching around types just to get something to "work". To that end, storing numeric data in a non-numeric type (e.g. varchar) will come back to bite you very soon. It's good you've opened this question to fix that!
As others have miraculously inferred, you are likely running into a localization issue. This is a great example of why storing numbers as strings is a problem. If you properly accept user input in whatever culture/localization they want (or you want), and get it into a numeric-type variable, then the rest (talking to the DB) should be easy. More so, you should not do number formatting in the database if you can help it--that stuff is much better placed at the front end, closer to the users.
I think your setting in windows regional and language for decimal symbol is wrong.please set it to dot and again test it.
This may help out for temporary use but I wouldn't recommend it for permanent use:
Try making it so that just before you save the file, convert the number to a string, replace the commas with periods (From , to .) and then save it into the database as the string, hopefully it should see that it is in the correct format and turn it into what the database sees as "Decimal" or "Floating".
Hope this helps.
Yep, localization.
That said, I think your pice is being stored on a "money" field in SQLServer (I'm assuming it's SQLServer you're using). If that was a float in the DB, it would return it with a normal decimal point, and not the European money separator ",".
To fix:
Fist DO NO USE FLOAT in your c# code, unless you absolutely require a floating point number. Use the decimal type instead. That's not just in this case, but in all cases. Floating point numbers are binary (base-2), not decimal (base-10), so what you see in the interface is only a decimal approximation of the actual number. The result is that frequently (1 == 1) evaluates as false!
I've run into that problem myself, and it's maddening if you don't know that can happen. Always use decimal instead of float in c#.
Ok, after you've fixed that, then do this to get the right localization:
using System.Globalization;
...
NumberFormatInfo ni = new NumberFormatInfo();
ni.CurrencyDecimalSeparator = ",";
decimal price = decimal.Parse(dbPriceDataField, ni);
Note that "dbPriceDataField" must be a string, so you may have to do a ".ToString()" on that db resultset's field.
If you end up having to handle other "money" aspects of that money field, like currency symbols, check out: http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx
If you need more robust error handling, either put that decimal.Parse in a try/catch, or use decimal.TryParse.
EDIT --
If you know what culture (really, country), the db is set to, you can do this instead:
using System.Globalization;
...
CultureInfo ci = new CultureInfo("fr-FR"); // fr-FR being "french France"
decimal price = decimal.Parse(dbprice, ci.NumberFormat);
Such problems were faced by me in my Web Apps... but i found the solution like I was fetching my price value in textbox. So I was have database attached with that. So when you attached your database with textbox... When you right click textbox and click Edit DataBinding.... in that you have to provide.... type like in Bind Property..... {0:N2}
This will work only for web apps or websites... not for desktop applications...
I have a brief discussion with my teammate regarding this. He says, if I enter a number in textbox, and try to use the value later on using textbox.text or val(textbox.text), I will not need to parse the value to integer. According to him, if the text attribute value is all number, you can directly get the value as integer, instead of string.
So, if I have textBox1.Text = "12345", then next time, if I use, intABC = textBox1.Text, it will not throw an error. Is it right? Does C# or other .Net language does this implicit conversion? Also, will the code store "12345" as string or integer? And how much memory will this value take, 5bytes for 5 characters or 2bytes for an integer?
TextBox.Text keeps the text as a simple string, it doesn't care about the real "meaning" of the string.
Then, if you want to have your number back, you need to parse the string, hence neither implicit nor explicit cast to int is allowed (or better, it will throw an exception if you do it...).
About the size, that text is stored as an UNICODE (UTF-16) string, hence from 2 to 4 bytes per character (depending on the character).
You can easily measure the size (just the size of the string, without the overhead due to reference size etc.) using the following code:
int numBytes = Encoding.Unicode.GetByteCount(stringToMeasure);
To find more info about strings, unicode and encodings have a look here, here or here .
your friend is wrong, it will make the compiler unhappy, the compiler won't even convert it automatically for you. Text property of a TextBox is of type string. check this
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.text.aspx
As to your question of other languages; if 'option strict' is not enabled, VB.NET will allow this. It will also allow this assignment if the input is not entirely numeric however, resulting in a runtime exception.
If you know you will only use numerical values, try using a NumericUpDown control.
You could then get/set the numerical value (decimal) by using the Value property.
A NumericUpDown control contains a single numeric value that can be incremented or decremented by clicking the up or down buttons of the control. The user can also enter in a value, unless the ReadOnly property is set to true.