toFixed() Simple use/explanation in text field - javascript

I've avoided asking this question here as I know many have in the past. I've spent some time during the last few days trying to find a solution/figure out how the toFixed() method works. I've read a lot of questions on this site and tutorials on others but I'm still not getting it.
I have several text fields with the class, ".entry". A dollar amount is supposed to go here. When people type the following (examples):
1.2
5
6.35
8.
I need them to change to:
1.20
5.00
6.35
8.00
In other words, add the trailing zeros. I know this is accomplished through the toFixed() method but I'm completely at a loss. I can't get it to work.
I have a script I found that totals all the text fields in a DIV elsewhere on the page and I notice that it uses the toFixed() method:
$("#total").html(sum.toFixed(2).replace(/(^\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,'));
}
I tried using that same code here so the zeros could display in the text field:
$('.entry').keyup(function(){
var str = this.value.replace(/(^\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1');
if (str!=this.value) this.value = str;
});
It doesn't work.
I'm new to Jquery and Javascript so I realize I'm probably missing something obvious. Most of the tutorials I've read set the variable in the code and then use "document.write" to display the variable with the correct number of zeros:
Example:
document.write( 1.1.toFixed(2) + '<br>' );
But this isn't what I'm looking for. I need it to show up in the text field.
Thanks in advance!

A few things:
Use the change event instead of keyup. If you use keyup, the text wil change every time the user tries to type something, which is an annoying user experience.
Consider using an input of type number with a step of 0.1.
With those in mind, I'd do something like this:
$('.entry').change(function(){
// parse the typed value as a floating point number
var num = parseFloat(this.value);
// ensure there are two decimal places
this.value = num.toFixed(2);
});
Note that if the user types something with more than two decimal places, the value will be rounded.
Example: http://jsfiddle.net/jndt1e02/

Related

converting a string to float doesn't work

I got a variable Javascrpit which has a number as a string in this case 0.84. I'm trying to convert it into a float but when I try to it appears a 0 as float instead the 0.84.
I'm using this:
var pot="0.84";
var asd = parseFloat(pot);
console.log(asd);
EDIT:
This is not exactly the example. I recover data from the HTML and it works for other numbers but not for this. It is difficult to explain my problem exactly. It is a lot of code and works for other numbers so don't know exactly.
Your input is not "0.84". If you test with that, you will get the correct answer. Your input has something else inside, like spaces, for example:
"0 .84"
This should be the solution:
parseFloat(pod.replace(/ /g, ""))
I have tried this example on my end and it completely worked. However, you can try to instead input the string value directly into the parse float() function and it should print our your expected value. If you still want to assign the parsefloat() to a variable, then try to either rewrite the code or re-open your IDE because the code should work.
var pot = "0.84"
console.log(parseFloat(pot))
or you can just write it in one line
console.log(parseFloat("0.84"))

Currency input with Twitter Bootstrap (using jQuery)

I'm using Twitter Bootstrap (v3) and I want to make a money input, where I can enter an amount of money with a fixed currency (currently €).
The input type needs to be type="number" because of how I want the input to look on mobile devices (not a big QWERTY keyboard, just numbers), but I do want to allow multiple patterns.
I think the way to go is with the .on("input", callback) method, but I'm not sure how to accomplish this.
I have tried the following:
$(document).ready(function() {
$("#amount").on("input", function() {
// allow numbers, a comma or a dot
$(this).val($(this).val().replace(/[^0-9,\.]+/, ''));
});
});
(for the HTML and CSS, see the jsfiddle link)
But obviously that doesn't work, otherwise I wouldn't be posting here. Whenever you try to type something invalid, the whole string disappears.
http://jsfiddle.net/bjcayhzb/1/
Explanation rather than (or alongside) a working example highly is appreciated.
It is the type of input field 'number' that comes in the way. It has its own keyup/input handler attached (modern browsers deal with it via JS code too) and seems to break things.
If you use
<input type="text" required="" placeholder="42,00" class="form-control" id="amount" />
then this works:
$(document).ready(function() {
$("#amount").on("input", function() {
// allow numbers, a comma or a dot
var v= $(this).val(), vc = v.replace(/[^0-9,\.]/, '');
if (v !== vc)
$(this).val(vc);
});
});
The only drawback of this approach is that if you try to put bad character in the middle of the string, cursor jumps to the end. And, of course, you can type multiple dots and commas.
Better approach would be to keep last good value stored in data and test the whole string and replace if new character invalidates match for the whole string.
Update
When input type="number" value contains non-number, jQuery val() returns empty string. This is why your code is not working. If "number" is a must (e.g. for numeric mobile keyboard), an approach would be to keep last known correct val() and put it back into control.

Regex replace anything but numbers with increments letter using javascript

I have an equation/formula stored in database and I want it to be triggered based on key up input event in a webpage.
Example formula: [55-57]
This is a simple minus operation, where the number actually represents the id of a row in database
I have looked at this solution which replaces numbers found in a string to new value. But I need the new value to be replaced with incremented letters such as a, b and so on. Also the leading and ending brackets [] need to be removed so that I can perform an eval later using JavaScript.
Later the equation will be convert to a-b. Variable a and b represent other HTML elements that holds a value. So whenever I key in something into text field, changes will reflect on other part of webpage. It's like auto computation.
Thank you for those helping this. Hope this question will help somebody.
Try something like this. If you need more help, you seriously need to re-word your question or post a jsfiddle, or something.
var eqn = '55-57'; // brackets removed. Remove them with a regex of /\[|\]/g if you need to
var result = eval( eqn.replace( /\w+/g, function( res ){
return +document.getElementById( res[1] );
} );
Basically this replaces 55 and 57 with the numerical values of #55 and #57. It would also work for #b, etc.
It then eval's the result, basically doing whatever math is in your equation.

Detecting number format culture settings

I have a webpage that needs to take numeric input, this part is easy enough with some combination of parseFloat, isNaN and (for displaying the values back to the user) toFixed. The problem is that Javascript seems to be completely ignorant of culture here. Some cultures use a decimal comma instead of a decimal point, but Javascript bulks at this.
Supporting the decimal comma isn't too much trouble, I can just replace a comma with a decimal point before parsing the users input and I can do the reverse before displaying the result to the user. My question is, is there a way for Javascript to know the users culture settings? I only care about the decimal separator, so for now I have no interest in other complications like thousands separators or currency.
Is there a reliable (client side) way to detect whether a visitor is using the decimal comma rather than the decimal point?
Update
In case anybody else wants it (or if anybody can see a flaw - other than not working in Chrome, as noted - or a better way), I ended up doing this:
var useComma = (0.1).toLocaleString().indexOf(",") > 0;
Now useComma will be true if the user has comma set as their decimal separator
I think that trying to detect the user's locale may not actually help that much. If your Web Application is in English language, a user might actually use English-style formatting (e.g. 1.3) even though in their own culture it would be formatted differently (1,3 for fr-FR or es-ES)! And who would blame them?
You could try and be smart and use the solution proposed by Alex K, and/or take into account the accept-language header, the locales matching your localizations (if any) and even GeoIP for a best guess. But to reduce confusion you may want to give your user cues whenever you expect them to enter numerals or dates or other locale-sensitive data.... Display a default value or an example next to the fields, formatted using the same locale as you will be using to parse user input.
If you believe it gives you better user experience to be flexible, you could use a fallback technique and try the formats you expect the most.
How about
var decimalChar = (0.1).toLocaleString().charAt(1);
Edit, this appears not to work in chrome Internationalization(Number formatting "num.toLocaleString()") not working for chrome
function browser_i18n() {
var o1 = new Intl.NumberFormat().resolvedOptions();
var o2 = new Intl.DateTimeFormat().resolvedOptions();
var o3 = new Intl.NumberFormat().formatToParts( 123456.789 );
return {
locale: o1.locale,
sign: o1.signDisplay,
group: o1.useGrouping,
timeZone: o2.timeZone,
calendar: o2.calendar,
thousands: o3[ 1 ].value,
decimals: o3[ 3 ].value,
}
}
//

Limit an html form input to a certain float range

Is there a way to limit a form input field to be between certain number range, say (0,100)
I'm filtering the input in the onkeydown event, to accept only numbers, the problem
is I want to reject a number if that number would make the input to go out of range
So I need a way to see if the current value of the input plus the key the user is pressing
will sum up between the range.
I tried using:
if((parseFloat(this.value) + parseFloat(String.fromCharCode(e.keyCode)) > 100){
return false;
}
the thing is e.keyCode can return different codes for the same number, right now is returning 57 for the
number 9, but 105 if i press the number on the numpad.
Is there a way to accomplish this?
Personally, I would just check it when the field loses focus (or when the form is submitted). Popping up errors as the user is typing (or preventing their keystrokes from registering in the field) is usually just going to annoy them.
And of course you probably knew this already, but make sure you check the value on the server side after the form is submitted as well. Never rely on javascript validation!
Trying to anticipate what the resulting value is going to be is harder than you think. Remember the user might be pressing backspace, or the cursor might not be at the end of the field, or the user might have part of the value selected, to be replaced on next keypress, and so on. It's also possible to manipulate the text field through mouse operations you won't get any say in.
The traditional approach is to put your validation on the ‘keyup’ event instead of ‘keypress’. Then you get the full, post-change value of the field. You don't get the chance to deny the keypress, but you can reset the field to the last-known-good value instead.
But either way it's best not to try to constrain input too tightly, because this can make it terribly difficult to type. For example, “12.” is an invalid number you might want to deny... but if you did, it would become very difficult to type “12.3”! Better to allow any input, but signal when the current input is out of bounds, by some mechanism (eg. turning the text red is common).
Adding the current value plus the float value of the character typed is not what you want. Think about if the current value is 99.0 and the user types a "5", the actual value is 99.05 but your expression would evaluate to 104.0. You need to append the key character to the current value before parsing anything into a float.
As for the key code, here is a reference to the javascript key codes. Using that you could write your own function like this:
function fromKeyCode(code) {
var asciiCode = code;
if (code > 95 && code < 106) {
asciiCode -= 48;
}
return String.fromCharCode(asciiCode);
}
var total = new Number(20.00);
alert(total.toFixed(2));
That will allow you to set a fixed width on the precision of 2 decimal places. In this case I am making sure with a js required field check that money only has 2 spots after the 2.
I'm not sure if I understand your question fully, but check the Number() methods, there has to be something there to help you.
You can catch the input on keyup, after the value contains the new input.
Then just look at the value-
inputelement.onkeyup= function(e){
e= window.event? event.srcElement: e.target;
var val= parseFloat(e.value) || 0;
e.value= Math.max(0, Math.min(100, val));
}

Categories