ideally this is for AS3, but I can always convert it down from JavaScript. Basically I want type numbers into a field and have it add the decimal. The issue is, the keyboard won't have a "." key
So if the final output was 10.45
it would automatically start to format as I type:
1 it would change to .01. And as I keep typing..
.01
.10
10.40
10.45
This can be accomplished by some simple string manipulation. Just split the string into parts and insert the decimal.
HTML
<input type="text" id="price" onchange="formatPrice(this)" />
Javascript
function formatPrice(obj) {
//remove any existing decimal
p = obj.value.replace('.','');
//get everything except the last 2 digits
var l = p.substring(-2, p.length-2);
//get the last 2 digits
var r = p.substring(p.length-2,p.length);
//update the value
obj.value = l + '.' + r;
}
You can see it working here: https://jsfiddle.net/x3wey5uk/
Related
I have two type="number" <input> elements, which I want to use to let people enter the hours and minutes parts of a time value in a mobile application.
By default, the two input element's value is 0, so they both show 0. This results in a display of 0:0. The usual representation however would be 0:00, so I would want the second input to show double digits.
Also, if the user enters a value below 10, I would still want the input to show the number padded with a 0.
I could imagine a couple of ways to do this with a text input field, but that would create the problem of validation. Also, I picked type="number" specifically, so the mobile OS will pop open the numeric input when the input element is focused.
You can use these code for number pad :-
function pad(n, width, z)
{
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
pad(10, 4); // 0010
pad(9, 4); // 0009
pad(123, 4); // 0123
I was testing a simple code to:
Get value of an input box
Do Mathematical operations on it...
My Code:
setInterval(function(){var a=document.getElementById("myInputBox").value;var b=a+1;a.value=b;},1000);
I am trying to add 1 to the value of that input box, every 1 second.
For example, if the box has value 1 ,then after 1 second it should become 2,....and so on.....
But it gets joined with the box's value, like 11 instead of 2.
Why is that?
Try with full code & demo:
get value from inputbox is a string, so it can't calculate mathematically. so, at first convert string to numeric by using function parseInt and then calculate and put into box.
setInterval(function() {
var box = document.getElementById("myInputBox");
var r = parseInt(box.value, 10) + 1;
box.value = r;
}, 1000);
<input type="text" id="myInputBox" value="1" />
var b = parseInt(a) + 1;
a is a string, so the + is interpreted as string concatenation by default. To fix, pass a to parseInt because it returns a type integer. Now the + becomes a math operator.
Extra Credit:
var b = parseInt(a, 10) + 1;
For an extra measure of integrity, pass the second (radix) argument, ensuring base 10 is used to determine the return integer value.
var valT = #TextToNumber("123,43");
getComponent("ValRamasa").setValue(valT);
The value returned is 0. and the component ValRamasa :
<xp:inputText id="ValRamasa" disabled="true">
<xp:this.converter>
<xp:convertNumber type="number"
maxFractionDigits="2" locale="ro">
</xp:convertNumber>
</xp:this.converter>
< xp:this.value><![CDATA[#{viewScope.field_2[index]}]]></xp:this.value>
</xp:inputText>
The converter is setted to my locale such that: , is the decimal separator and . is the thousand separator.
If I try var valT = #TextToNumber("123.43"); => 123,43.
Why I tried the above example? I have an input field ( whith locale="ro" ) where the user can add some number ( with , as the decimal separator ), and with this value I want to do some math calculations, but I noticed the above issue occurs.
My calculations ( I'm using a repeat control ):
var number = getComponent("inputText11").getValue();
var procent = getComponent("inputText19").getValue();
for(var i = 0;i<=index ;i++){
// ****** val - is the 'problem' value **** IF val = integer => it works / IF val = decimal ( with , as decimal separator ) => IT don't works
var val = viewScope.field_1[i];
/* <xp:inputText id="inputText23">
<xp:this.value><![CDATA[#{viewScope.field_1[index]}]]></xp:this.value>
<xp:this.converter>
<xp:convertNumber type="number" locale="ro" maxFractionDigits="2">
</xp:convertNumber>
</xp:inputText>*/
//val = val.replace(",",".");
val = #TextToNumber(val);
//number = Number(number) - Number(val);
number -= val;
var garantie = procent*val/100;
}
//var valT = #TextToNumber("123.43");
getComponent("ValRamasa").setValue(number);
getComponent("ValGarantie").setValue(garantie);
#TextToNumber is for sure not your problem here.
The component you deal with is of type number, meaning, that it is STORED as a number -regardless of any "display" properties.
For sure you have an implicit text- conversion somewhere and try to convert this text back:
Then the locale settings will be ignored and an error will raise.
In your posted code for the calculation, there is also no obvious error.
But: where do the values in "viewScope.field_1" come from? I guess, that there is "Text" in these variables, that causes this issue.
#TextToNumber does not follow any locale settings as this is a program language. To convert a number into text your number must follow the guidelines of the language, in this case you have to use the colon . in your number as decimal separator. If you'd use this formula e.g. in a view column you'll get an error message - try it!
The converter of a field is used to convert and accept the typed in value.
Lets say I have an amount in string format like this:
amount = '12,000.00'
I want to convert it into a Number (Javascript) or a float.
parseFloat(amount) // this gives me 12 as a result
Number(amount) // this gives me NaN as a result
Other solution I thought was this:
parseFloat(amount.replace(/[,]/g, ''))
This works fine. But the problem here is the Locale.
This would fail when the amount is € 12000,00.
Here ',' has altogether a different meaning.
I looked around for a good solution but couldn't. I am looking for a generalized solution.
This is not that easy, as you can't exactly know what's the delimiter for thousands and what for the decimal part
Consider "12.000.000" is it 12000.000 === 12000 or 12000000?
But if you would set the requirement that the last delimiter is always the decimal delimiter -
meaning if at least one delimiter is given, the last one has to be the decimal delimiter, *if the digits following, don't exceed a defined length.
Then you could try the following
Edit
(see the revs if you're interested in the old function)
I put in the ability to define the max length of digits after the last delimiter "," or "." up until it is treated as float, after that its returned as integer
var amounts = ["12000","12.000,00", "12,000.00", "12,000,01", "12.000.02", "12,000,001"];
formatMoney.maxDecLength = 3; //Set to Infinity o.s. to disable it
function formatMoney(a) {
var nums = a.split(/[,\.]/);
var ret = [nums.slice(0, nums.length - 1).join("")];
if (nums.length < 2) return +nums[0];
ret.push(nums[nums.length - 1]);
return +(ret.join(nums[nums.length - 1].length < formatMoney.maxDecLength ? "." : ""));
}
for ( var i=0,j;j=amounts[i];i++)
console.log (j + " -> " +formatMoney(j));
Gives the output:
"12000 -> 12000"
"12.000,00 -> 12000"
"12,000.00 -> 12000"
"12,000,01 -> 12000.01"
"12.000.02 -> 12000.02"
"12,000,001 -> 12000001" //as you can see after the last "," there are 3 digits and its treated as integer
Another JSBin
You can get the local decimal delimiter in this manner:
1.1.toLocaleString().substr(1,1)
Before parse float, you could make sure the string contains nothing but numbers, possibly a minus sign, and the local decimal delimiter.
The truth is, you'll never know the format. 12,345. Is that 12345, or another locale version if 12.345?
However, if you have consistent decimals, then you'd be able to use the lastIndexOf function on a comma and a period will reveal the decimal position and character.
var price = '12,345.67';
var lastPeriod = price.lastIndexOf('.');
var lastComma = price.lastIndexOf(',');
if (lastComma != -1 && lastComma > lastPeriod) {
decimalCharacter = ',';
} else {
decimalCharacter = '.';
}
console.log(decimalCharacter); //. or , based on how the price string looks - see below
If price is 12,345.67, decimalCharacter will be .. If it's 12.345,67, it'll be returned as ,.
Hye,
Iam new to javascript working with one textbox validation for decimal numbers . Example format should be 66,00 .but if user type 66,0 and dont type two zero after comma then after leaving text box it should automatically append to it .so that it would be correct format of it . How can i get this .How can i append ?? here is my code snippet.
function check2(sender){
var error = false;
var regex = '^[0-9][0-9],[0-9][0-9]$';
var v = $(sender).val();
var index = v.indexOf(',');
var characterToTest = v.charAt(index + 1);
var nextCharAfterComma = v.charAt(index + 2);
if (characterToTest == '0') {
//here need to add
}
}
Use .toFixed(2)
Read this article: http://www.javascriptkit.com/javatutors/formatnumber.shtml
|EDIT| This will also fix the issue if a user types in too many decimals. Better to do it this way, rather than having a if to check each digit after the comma.
.toFixed() converts a number to string and if you try to convert it to a float like 10.00
then it is impossible.
Example-
10.toFixed(2) // "10.00" string
parseFloat("10.00") // 10
Number("10.00") // 10