How to append an extra 'Zero' after decimal in Javascript - 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

Related

Converting number string to comma version

I have a Angular 2 / Typescript application string that contains number representations such as the following...
10000
10000.50
-10000
-10000.50
0
I want to add in commas after the thousand mark, for example...
10,000
10,000.50
-10,000
-10,000.50
0
What is the best way to do this?
I have tried some other answers but nothing is quite right.
For example this.value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); and this.value.toLocaleString(); don't seem to handle both the comman and decimal point.
Have you tried
var some_string_value = '-10000.50';
parseFloat(some_string_value).toLocaleString()
?
Use "indexOf('.')",splice to two part,then use the method you found.
function addComma(num){
//some type check here
var numStr = num.toString();
var intEnd = numStr.indexOf('.');
var onePart =numStr,otherPart ='';
if(intEnd !== -1){
var onePart = numStr.slice(0,intEnd);
var otherPart = numStr.slice(intEnd);
}
return onePart.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')+otherPart;
}
You can use a pipe, you can find a full answer to your question here: Add Comma Separated Thousands to Number Inputs in Angular2

Javascript: Most Efficient way to convert string to integer then back to string

I have a text input field which has a value of text to take in a string like "$2,000." In my functionality, I need to convert this back to a a number to run some mathematical functions and then spit it out back as another dollar value, which will be formatted like "$2,500.56" (I.E. not "$2,500.567"). Here's the two tests I've run so far:
var amount = "$2,000.58"
// "2000.58"
var amount_no_sym = amount.replace(/[^\d\.]/g, '');
//2000.58
var amount_integer = parseFloat(amount_no_sym);
//2000.58 (will cut out any additional decimal places)
var amount_decimals = amount_integer.toFixed(2);
//Final output is "$2,000.58" - the toLocaleString doesn't add back the , here?
var amount_dollar_string = "$" + amount_decimals.toLocaleString();
var amount = "$2,000.58"
// "2000.58"
var amount_no_sym = amount.replace(/[^\d\.]/g, '');
// 2000.58
var amount_integer = parseFloat(amount_no_sym);
//Final output is "$2,000.58"- but sometimes it will be something like "$3,564.345" for certain calculations.
var amount_dollar_string = "$" + amount_integer.toLocaleString();
Would the most optimal solution be to go to the second one, and then write a function to process a string and cut off the last number after the decimal if there are more than two....? Is there a simpler way and I'm doing too much work?
Thanks in advance!
Don't do your own number formatting. There's an API for that.
var formatter = new Intl.NumberFormat("en-us", { style: "currency", currency: "USD" });
console.log(formatter.format(2000.58));
In both cases you can avoid calling the function parseFloat() by using Unary + (plus) operator which attempts to convert the operand to a number, if it is not already. And to format currency you can also use Number.prototype.toLocaleString() passing as arguments the desired locale and an object with options:
var amount = '$2,000,344.58',
amount_integer = +amount.replace(/[^\d\.]/g, ''),
amount_dollar_string = amount_integer.toLocaleString('en-EN', {
style: 'currency',
currency: 'USD'
});
console.log(amount_integer);
console.log(amount_dollar_string);

jquery comparing 2 integers

My submit click function is as below.
aAmt is a $ field like for eg. $45.00
a_amount is always 10000.
I am converting a_amount to $ in displayCurrencyFormat function.
I am then converting both to parseInt and doing >= comaprison and it fails. Even though aAmt is > $10000 and conition should display alert it doesnt.
$("#submitId").click(function () {
var aAmt = $("#aAmt").val();
var a_amount = "${dAmt}";
a_amount = displayCurrencyFormat(a_amount);
var pLen = $("#pOd").val();
if ((parseInt(aAmt) >= parseInt(a_amount)) && (pLen.length == 0)) {
$('#pDiv').text('Please provide a password');
$("#pOd").focus();
return false;
}
...//
});
function displayCurrencyFormat(a_amount)
{
//convert amount to currency format
var nbrAmt = Number(a_amount.replace(/[^0-9\.]+/g,""));
var fmtAmt = '$' + nbrAmt.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
return fmtAmt;
}
You should convert it into an integer-like data first, and then you can compare them.
The currency formatted input are considered as not a number format so comparing them are something like String to String comparison, not Number to Number like what you want to achieve.
Refrence link: How to convert a currency string to a double with jQuery or Javascript?
Do you know that parseInt('$10000') actually giving you "NaN"?
And as i can see here you are trying to compare integer and string...
Just try to alert aAmt and a_amount variables before you compare them and you will see what is actually going on...

JavaScript function to add two numbers is not working right

My code in HTML takes a user input number in, and it does a calculation and then displays the output. The user chosen input is put into a formula and the result of the formula is added to the user input number, but when it adds the two number together it's adding a decimal spot.
For example, if the number 11 is chosen, the result of Rchange is 0.22, so .22 is then added 11 to be 11.22 for newResistance, but instead it is displaying the value as 110.22 instead.
function calc(form) {
if (isNaN(form.resistance.value)) {
alert("Error in input");
return false;
}
if (form.resistance.value.length > 32) {
alert("Error in input");
return false;
}
var Rchange = .01 * 2 * form.resistance.value;
var newResistance = (form.resistance.value + Rchange);
document.getElementById("newResistance").innerHTML = chopTo4(newResistance);
}
function chopTo4(raw) {
strRaw = raw.toString();
if (strRaw.length - strRaw.indexOf("0") > 4) strRaw = strRaw.substring(0, strRaw.indexOf("0") + 5);
return strRaw;
}
HTML DOM element properties are always strings. You need to convert them to numbers in your usage.
parseInt(form.resistance.value);
parseFloat(form.resistance.value);
+form.resistance.value;
(Any of the three will work; I prefer the first two (use parseInt unless you're looking for a float).)
Try newResistance = +form.resistance.value + Rchange;. This will convert it to a number.
It's because it's treating the values as a string.
form.resistance.value + Rchange are both strings, so it's appending it.
Use the parseInt JavaScript method to get the decimal version.

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

Categories

Resources