I currently have a script that pulls a parameter from the url and displays on the page. My problem is that I need to format the decimal place for the value.
UPDATED (This is working now. Thank you all.)
Code
$(document).ready(function () {
var url = $.url('https://www.google.com/blah/blahblah/index.htm?x=50.5200');
var x = url.param('x');
var x2 = parseFloat(x).toFixed(2);
$("#value").text(x2);
});
Try this:
var decimal = '50.5230';
var num = parseFloat(decimal).toFixed(2);
console.log(num);
Related
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"));
I've run into some problems accessing and forwarding an ID.
I successfully extracted the ID from my URL but I run into problems if the URL contains unpredictable numbers aswell.
To clear things up a bit:
My efforts to extract the ID so far (JS)
var idString = window.location.href;
idString = idString.replace(/e107/gi, "__ersetzt__");
idString = idString.replace("http://localhost/Westbomke/backendV5/", "");
idString = idString.replace(/[^0-9]+/g, "");
Some URL examples
Working:
http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php Result: 235 = id
Not working:
localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event01/page.php
localhost/Westbomke/backendV5/e107-master/e107_projekte/company1337/235_Projekt_1337Event/page.php
now if I could exclude the /******_Projekt_ Part (**** = random amount of numbers) and parse it into an Integer I would be fine, but I dont know how to do this or if it's possible.
I tried to find something on here and via google but I most likely dont ask for the right stuff.
Thanks for your time and help in advance!
You can try with:
var url = 'http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php';
var id = +url.match(/\/(\d+)/)[1];
Is this URL you are working on stable in terms of structure?
If you are nto familiar with Regular Expressions and the Structure is pretty stable , then the following code will do the job for you:
var myString = "http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php";
var mySplitString = myString.split("/");
var myNumber = parseInt(mySplitString[8]);
console.log(myNumber);
Adding the below Function which will provide you with a bit more flexibility.
var myString = "http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php";
function getProject(myString , myDist){
var mySplitString = myString.split("/");
var myID = '';
mySplitString.forEach(function(key , index){
if(key.indexOf(myDist) > 0)
myID = parseInt(mySplitString[index]);
});
return myID;
}
var myID = getProject(myString , "Projekt");
console.log(myID);
I have a series of pages where I need to get a specific code for a button.
I want to put the code which is in the url into a variable with jQuery.
An example URL is www.example.com/folder/code/12345/
I want to get the number part in a variable called (siteCode)
Thanks in advance for any answers.
jquery / Pseudo code:
var siteCode;
// start function
function imageCode(){
siteCode // equals number part of URL
$('.button').attr('src', 'http:www.example.com/images/'+siteCode+'.jpg');
}
You can use the following code to get the last part of the url.:
var value = url.substring(url.lastIndexOf('/') + 1);
I'd suggest:
var URI = 'www.example.com/folder/code/12345/',
parts = URI.split('/'),
lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();
JS Fiddle demo.
var str="url";
str.split("/")[3]
you can use split
There is one best way to take last part of URL is like following which generally has been used in real implementation.
There are Some loopholes in previously given answer was:
1.Consider what if there is a url like www.example.com/folder/code/12345 (Without '/' forward slash) Than none of the above code will work as per expectation.
2.Consider if folder hierarchy increases like www.example.com/folder/sub-folder/sub-sub-folder/code/12345
$(function () {
siteCode = getLastPartOfUrl('www.example.com/folder/code/12345/');
});
var getLastPartOfUrl =function($url) {
var url = $url;
var urlsplit = url.split("/");
var lastpart = urlsplit[urlsplit.length-1];
if(lastpart==='')
{
lastpart = urlsplit[urlsplit.length-2];
}
return lastpart;
}
Also try using regex
var url = "www.example.com/folder/code/12345";
var checkExt = /\d$/i.test(url);
if (checkExt) {
alert("Yup its a numeric");
} else {
alert("Nope");
}
I am adding a users input in to UI as they add numbers and returning the results. The input is currency so I need to carry it out two decimals and not round.
Here is an example of my code:
function ceiling2(number) {
var ceiling2;
return ceiling2 = Math.ceil(number*100)/100;
}
//Totals
function lD23Total (e){
var app = UiApp.getActiveApplication();
var tB1v = parseInt(e.parameter.TextBox1);
var tB9v = parseInt(e.parameter.TextBox9);
var tB17v = parseInt(e.parameter.TextBox17);
var tB25v = parseInt(e.parameter.TextBox25);
var tB33v = parseInt(e.parameter.TextBox33);
var tB41v = parseInt(e.parameter.TextBox41);
var tB49v = parseInt(e.parameter.TextBox49);
var lD23 = app.getElementById("LabelD23").setStyleAttribute('fontWeight','bold');
var lD23T = tB1v + tB9v + tB17v + tB25v + tB33v + tB41v + tB49v;
lD23.setText("$ " + ceiling2(lD23T));
var app = UiApp.getActiveApplication();
app.close();
return app;
}
Currently it returns a rounded number.
I appreciate an suggestions you may offer!
Jon
The function parseInt() will convert the value to an integer, dropping the values after the decimal. Use parseFloat() instead.
I think your function is just fine...
if you remove the parseInt() and replace it either with parseFloat()as suggested by Eric or by Number() it should work...
if not then the problem might come from the way numbers are written:
If you used 26,4567 but you should use 26.4567 with a dot as separator in place of a comma.
Could you try and keep us informed ?
regards,
Serge
Or you can use this before sending to your function:
var newnumber=Number(number.toString().replace(",","."));// convert to string, replace comma with dot and set as number again.
and your function will work in both cases
How do you format a number to show 2 decimals in JavaScript?
Something along the lines of:
format(x,"9,999.99");
You should use this :
x.toFixed(2);
or if you want to be sure it will work :
parseFloat(x).toFixed(2);
var num = 3.14159;
var fixed = num.toFixed(2);
If you want the commas depending on the locale:
var localed = num.toLocaleString();
Combining both crudely:
var num = 3.14159;
var fixed = num.toFixed(2);
var fixednum = parseFloat(fixed);
var localedFixed = fixednum.toLocaleString();
Use .toFixed(2):
http://www.devguru.com/technologies/javascript/17443.asp
Note this will round your number:
var i = 23.778899;
alert(i.toFixed(2));
gives you
23.78
I'm not sure if you are trying to do this to input or just for displaying text on the page. You can use the masked input plugin for jQuery if you are trying to format input.
http://digitalbush.com/projects/masked-input-plugin/