copy decimal number value to a compponent - javascript

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.

Related

Formatting Price Input

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/

Subtraction working in JS but Addition is not working in JS

I can't seem to figure out why the subtraction is working in my code, but when I change the subtraction sign to an addition sign, I get a console error: Uncaught TypeError: undefined is not a function. Where is the error?
Here is a fiddle with the subtraction: http://jsfiddle.net/c8q7p6ac/
Here is a fiddle with the addition in place of the subtraction sign: http://jsfiddle.net/c8q7p6ac/1/
The subtraction sign and the addition sign are in the variable updatedNumber
HTML:
<div class="amount">$1000.00</div>
<input class="new-number" type="text">
<div class="button">Click</div>
jQuery:
$('.button').on('click', function(){
//get value of input
var newNumber = $('.new-number').val();
//get total number value
var totalNumber = $('.amount').text();
var getNumberOnly = totalNumber.indexOf('$') + 1;
var newTotalNumb = totalNumber.substr(getNumberOnly, totalNumber.length);
//add new number to total number
var updatedNumber = (newTotalNumb + newNumber).toFixed(2);
//and update total
$('.amount').html('$'+updatedNumber);
});
The subtraction works because JavaScript converts them to numbers. However, in case of addition, it converts them to strings as soon as one of the operands is a string.
You need to convert the string to a number:
var updatedNumber = (parseInt(newTotalNumb) + parseInt(newNumber)).toFixed(2);
While dealing with decimal points, you can also use parseFloat which will preserve the decimal points.
Here's the updated fiddle.

Javascript: Convert a string representation of money to Number

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 ,.

Adding a 0 before decimal entered in input?

I'm attempting to finish up a quick form using jQuery that needs to add a 0 before a decimal point if the decimal is the first char entered in the input.
For example,
.25 would become 0.25 before the form is submitted.
However, 2.05 would stay as 2.05, and no 0 would be added.
Is there a simple function here that could help me out? I'd rather not write something long and detailed if it's not necessary.
Also, here is the input box that I am asking for help with, for reference
<input type="number" name="dailygain" id="dailygain" />
You can use parseFloat function to format float numbers.
var el = document.getElementById("dailygain");
el.value = parseFloat(el.value);
Multiply by 1 (*1) to make it numeric.
If you make it a number, it'll do it for you automatically; formatting based on your systems locale.
Example:
var x = '.25';
console.log( x*1 ); // 0.25
The same can be accomplished with a unary plus (e.g., console.log( +x ); )
Put this in a function run onsubmit.
var num=$("#dailygain").val(); //read the number from the textbox
num=num.toString(); //convert that number to a string
if (num.charAt(0)==".") //check if the string starts with a period
num="0"+num; //if so, add a 0 in front of it
$("#dailygain").val(num); //write the number back to the tb
parseFloat is probably more suited, but anyway :
$('#dailygain').on('keyup', function() {
if (this.value[0] === '.') this.value = '0'+this.value;
});
FIDDLE
​
$("input[name=dailygain]").keyup(function(){
var val = this.value;
if(val.charAt(0) === '.'){
this.value = ('0'+val);
}
});
http://jsbin.com/ofivun/2/edit

How to append an extra 'Zero' after decimal in Javascript

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

Categories

Resources