How to add formatting to javascript's number display globally - javascript

In Javascript I have a number and I want to add comma to it when it's displayed as a string.
I can add comma to the number like this:
function numberWithCommas(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
But I don't want to call a method on every number that we have to get this. I want to do something similar to this:
Number.prototype.toString = function(radix) {
return numberWithCommas(this);
}
So when I do the following, the right value will show up:
var num = 100000;
alert(num); // 100,000
Can't get the above to work. Any ideas?

What about creating a new number function?
Number.prototype.withCommas = function(){
return this.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
var n = 1234567;
alert( n.withCommas() );
http://jsfiddle.net/kyX8x/1/

Related

Calculating 2 values from fields but it's not working properly

I am calculating 2 fields on a form with values but it seems in some cases it's not working. Here's my javascript. I am adding $oneTimeCostField and $recurringTotalCostField to get the value into the $totalRetailAmountField. Here's the result I am getting when I add say 1,555.00 + 566.00 = the value is 567.00 (?). Any idea what I'm doing wrong? In some cases it works correctly when the values are lower. Thanks, just stumped
var $recurringCostField = $('#am_attribute_campaign_addon_monthly_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_oie_string_total_monthly_cost_value');
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseFloat(num1) + parseFloat(num2);
if (!isNaN(result)) {
$totalRetailAmountField.val(result.toFixed(2));
}
}
calcVal();
$oneTimeCostField.on("keydown keyup", function() {
calcVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcVal();
});
You need to remove the commas before parsing:
var result = parseFloat(num1.replace(/,/g, '')) + parseFloat(num2.replace(/,/g, ''));
similiar question on this link
Remove commas from the string using JavaScript
That is because parseFloat() converts the string "1,555.00" to the number 1.
To convert it to a proper floating point number, it needs to include a single dot only.
console.log(parseFloat("1.555"));

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

Obtain numbers from a field and process them

I have a field which obtains it input through a list of links associated with numbers. (Similar to a calculator but without operators). I want to retrieve these numbers and put them through a function which divides them by 12. (A conversion from feet to inches).
First I have a list of jQuery click functions like this:
$('#a0').click(function(){
writeInput(input, one); // var one = 1;
});
Next I have the function "write Input" (This is where the numbers are displayed on a "screen")
function writeInput(field, str){
$input = $(field);
var text = $input.val($input.val() + str);
$input.text(text);
convert(text);
}
And lastly I have a function which is supposed to divide the number inputted by 12
function convert(input){
var divide = (input / 12);
$("#output").html(divide); //output is a paragraph where the number is displayed
}
When I run my code I am getting NAN output where the number should be. I have tried parseInt() and other tricks. But the closest I have come to something correct is when I got [object] [object] output.
Any help would be appreciated. Thanks!
In your code text is a jQuery object, you are using val as setter which returns a jQuery object, you should use val/text method as a getter for retrieving updated value.
function writeInput(field, str){
var text = $(field).val(function(i, v){
return v + str;
}).text(function(i, t){
return t + str
}).val();
convert(text);
}

How to achieve String Manipulation in JavaScript

The problem statement is like this: I have a contract. On renewal on every month the contract name should append with renewal identifier. For example at beginning the name is myContract then on first renewal name should be myContract-R1, next renewal name should be myContract-R2 and so on.. On each renewal, the name should automatically change. So in Jquery how can I do this?
This is a JavaScript question, not a jQuery question. jQuery adds little to JavaScript's built-in string manipulation.
It sounds like you want to take a string in the form "myContract" or "myContract-Rx" and have a function that appends "-R1" (if there's no "-Rx" already) or increments the number that's there.
There's no shortcut for that, you have to do it. Here's a sketch that works, I expect it could be optimized:
function incrementContract(name) {
var match = /^(.*)-R([0-9]+)$/.exec(name);
if (match) {
// Increment previous revision number
name = match[1] + "-R" + (parseInt(match[2], 10) + 1);
}
else {
// No previous revision number
name += "-R1";
}
return name;
}
Live copy
You can use a regular expression for this:
s = s.replace(/(-R\d+)?$/, function(m) {
return '-R' + (m.length === 0 ? 1 : parseInt(m.substr(2), 10) + 1);
});
The pattern (-R\d+)?$ will match the revision number (-R\d+) if there is one (?), and the end of the string ($).
The replacement will return -R1 if there was no revision number before, otherwise it will parse the revision number and increment it.
how you get renewal number? Calculating from date, or getting from database?
var renewal = 1,
name = 'myContract',
newname = name+'R'+renewal;
or maybe like
$(function(){
function renew(contract){
var num_re = /\d+/,
num = contract.match(num_re);
if (num==null) {
return contract+'-R1';
} else {
return contract.replace(num_re,++num[0]);
}
}
var str = 'myContract';
new_contract = renew(str); // myContract-1
new_contract = renew(new_contract); // myContract-2
new_contract = renew(new_contract); // myContract-3
});
Here jQuery can't help you. It's pure JavaScript working with strings
P.S. I have here simple reg exp, that's not concrete for your example (but it works). Better use reg-exp from example of T.J. Crowder

Adding characters to string (input field)

I have a text box where the value is the result of a calculation carried out in jQuery. What I would like to do, using jQuery, is to display brackets around the number in the text box if the number is negative.
The number may be used again later so I would then have to remove the brackets so further calculations could be carried out.
Any ideas as to how I could implement this?
Thanks
Zaps
function FormatTextBox(id) {
var txtBox = $(id).val();
//strip bracket to get the number only
txtBox = txtBox.replace("[", "").replace("]", "");
var val = parseFloat(txtBox);
if (val < 0) {
txtBox.val("[" + val + "]");
} else {
txtBox.val(val);
}
return val;
}
First, store your calculation in a variable. You shouldn't be using the DOM to store data (in most cases). This basically eliminates your problem.
Number.prototype.bracketed = function() {
if(this < 0) {
return '[' + -this + ']';
} else {
return '' + this;
}
};
var result = do_calculation();
myTextBox.value = result.bracketed();
// result still holds the original Number value.
If you really want to store the data as the .value of the text input, you can make an unbracketed function as well:
String.prototype.unbracketed = function() {
var parts = this.match(/^\[([0-9]+)\]$|^([0-9]+)$/); // [number] or number
if(parts[1]) { // [number]
return -parseInt(parts[1], 10);
}
if(parts[2]) { // number
return parseInt(parts[2], 10);
}
return NaN;
};
Assuming you might have multiple fields (and you don't want the negative sign):
jQuery('input').each(function(){
if(jQuery(this).val() < 0 ){
jQuery(this).val('['+-1*jQuery(this).val()+']');
}
}
)
Then when you grab the value again, just strip the brackets and multiply by -1 to make it negative.
EDIT:
You can also use jQuery('input').data() to store the original number so you don't have to parse it again. (read more: http://api.jquery.com/data/ )

Categories

Resources