Adding a 0 before decimal entered in input? - javascript

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

Related

I want my value modified to always have three decimal digits

My logic calculates and returns a value based on user input, I want to modify that value to always have three decimal digits
For example;
1 to 1.000
1.02 to 1.020
2.000004 to 2.000
2.5687 to 2.569
How would I achieve it on javascript?
You can use Number().toFixed() to do it
const formatVal = (val,precise = 3) =>{
return Number(val).toFixed(precise)
}
console.log(formatVal(1,3))
console.log(formatVal(1.02,3))
console.log(formatVal(2.000004,3))
console.log(formatVal(2.5687))
console.log("-----------------")
console.log(formatVal(2.5687,2))
You can do something like this,
let newNum = Number(1.34).toFixed(3);
console.log(newNum);

Javascript Floating Number Comparison

I'm trying to do what I thought was pretty straight forward but having odd results. I have two fields on a page: transactionAmount and transactionLimit. When the button is clicked, it calls a javascript function that makes sure the amount isn't greater than the limit:
var transactionAmount = parseFloat(document.getElementById("amount").value).toFixed(2);
var transactionLimit = parseFloat(document.getElementById("limit").value).toFixed(2);
if (transactionAmount > transactionLimit) {
alert("Over limit");
}
If I set the transactionAmount to be $2.00 and the transaction Limit to be $100.00, I get the over limit alert. If I set the transactionAmount to be $1.00 then it works fine. Basically any other value less than $1.00 works if the limit is $100.00 but anything over $1.00 gives me the error.
Would be grateful for some insight! Thank you!
The main problem happening because of toFixed(2) it converts your result to string that's why your condition is not working as you expected. just wrap it with preceding + character to make it Number from String
var transactionAmount = +(parseFloat('2.00').toFixed(2));
var transactionLimit = +(parseFloat('100.00').toFixed(2));
console.log(transactionAmount,transactionLimit, typeof transactionAmount,typeof transactionLimit )
if (transactionAmount > transactionAmount ) {
console.log("Over limit");
}
Try to add the function "Number()" to you values, toFixed() actually transform them to string. You can also add a "+" before to do the same action.
Example:
var transactionAmount = Number(parseFloat("150.00").toFixed(2)); //or: +parseFloat("150.00").toFixed(2)
var transactionLimit = Number(parseFloat("100.0").toFixed(2)); //or: +parseFloat("100.0").toFixed(2)
if (transactionAmount > transactionLimit)
{
alert("Over limit");
} else {
alert("you ok dude");
}
Output:
"Over limit"
I hope it helps you!

copy decimal number value to a compponent

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.

How to get jQuery animateNumber to pull value dynamically?

I am trying to implement jQuery animateNumber, and I have it working like the demo just fine. However, I want to modify it so that it pulls the number from the HTML, rather than setting it in the script. I tried the following, but it just shows "NAN." What am I doing wrong?
<div class="stat-title animate-number">$16,309</div>
<script>
$('.animate-number').each(function(){
var value = new Number;
// Grab contents of element and turn it into a number
value = $(this).text();
value = parseInt(value);
// Set the starting text to 0
$(this).text('0');
$(this).animateNumber(
{
number: value,
},
1000
)
});
</script>
ParseInt is failing because of the $ character. Also, the comma is messing with parseInt and giving you the value 16 instead of 16309. After that, the animation seems to be working. Also, you don't necessarily have to replace it with 0 since animateNumber automatically starts from 0. Here's my work so far on JSfiddle:
http://jsfiddle.net/0m9828kn/1
$('.animate-number').each(function(){
var value = $(this).text();
value = value.substring(1, value.length);//Remove $ sign
value = value.replace(/,/g, "");//Remove all commas
value = parseInt(value);
//$(this).text("0"); //This part isn't actually necessary
$(this).animateNumber(
{
number: value
},
1000
)
});
Looks like the problem is that ParseInt is choking on the dollar sign. Then when you remove that, it only reads up to comma and animates to 16. Take them both out, and it works.
value = $(this).text().replace(/[\,\$]/g,'');
But, you'll need to include this option to get your comma back:
var comma_separator_number_step = $.animateNumber.numberStepFactories.separator(',')
$(this).animateNumber(
{
number: value,
numberStep: comma_separator_number_step
},
1000
)
To get your dollar sign back, you could change your html to something like this:
<div>$<span class="stat-title animate-number">16,309</span></div>

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