Convert String to Float in Javascript error - javascript

Please see below code,i getting wrong value.
eg;
var FirstValue=0.00;
var secondvalue=parseFloat("22.88",10).toFixed(2);
var thirdvalue=(FirstValue) + (secondvalue);
am getting value like"22.8822.88"
Please help me to solve.Its not convert to numeric .

toFixed convert you float value to string back. So when you adding two values you will get not number addition but string concatenation:
2.0 + 2.0 = 4.0 // number
"2.0" + "2.0" = "2.02.0" // string
Remove to fixed after conversion. Than add two values and than do to fixed:
var FirstValue=0.00;
var secondvalue=parseFloat("22.88",10);
var thirdvalue= ( (FirstValue) + (secondvalue) ).toFixed(2);

try this:
var FirstValue=0.00;
var secondvalue=parseFloat("22.88");
secondvalue = parseFloat(secondvalue.toFixed(2));
var thirdvalue=(FirstValue) + (secondvalue);
toFixed returns a string, not a number so it needs to be converted again.

Related

Why I can't perform the toFixed() function after the sum of 2 retrieved values?

Into a JQuery script I have the following problem trying to use the toFix() JavaScript method on a number.
So I have the following situation:
var anticipoProgetto = $("#valoreAnticipo").text();
var saldoProgetto = $("#valoreSaldo").text();
var anticipoCalcolato = (saldoProgetto + anticipoProgetto);
console.log("ANTICIPO CALCOLATO: " + anticipoCalcolato);
anticipoCalcolato = anticipoCalcolato.toFixed(2);
$("#anticipoModaleUlterioreSaldo").val(anticipoCalcolato);
The console.log() show:
ANTICIPO CALCOLATO: 2192.002200.37
So it means that JavaScript have correctly perform the addition.
The problem is that wehn try to perorm this line to obtain a value with only 2 decimals digits:
anticipoCalcolato = anticipoCalcolato.toFixed(2);
in the FireBug console I obtain this messagge error:
TypeError: anticipoCalcolato.toFixed is not a function
anticipoCalcolato = anticipoCalcolato.toFixed(2);
Why? What am I missing? How can I fix this issue?
The math is wrong because you are adding two string together, not two numbers. And he toFixed error is because you are trying to use toFixed on a string, but that ethod only exists on numbers.
Convert the strings to numbers when you read the .text()
var anticipoProgetto = parseFloat($("#valoreAnticipo").text()),
saldoProgetto = parseFloat($("#valoreSaldo").text()),
anticipoCalcolato = anticipoProgetto + saldoProgetto,
fixed = anticipoCalcolato.toFixed(2);
#espacarello is correct, you need to cast from string to number. It may be more to your intent to cast them as you read them.
If #valoreAnticipo is an input element, consider switching to .val() instead of .text()
var anticipoProgetto = parseFloat($("#valoreAnticipo").text()) || 0;
var saldoProgetto = parseFloat($("#valoreSaldo").text()) || 0;
var anticipoCalcolato = (saldoProgetto + anticipoProgetto);
console.log("ANTICIPO CALCOLATO: " + anticipoCalcolato);
anticipoCalcolato = anticipoCalcolato.toFixed(2);
$("#anticipoModaleUlterioreSaldo").val(anticipoCalcolato);

Sum code not working properly [duplicate]

This question already has an answer here:
Function sum not working properly javascript [duplicate]
(1 answer)
Closed 7 years ago.
I'm trying to redirect from www.domain1.com to www.domain2.com getting the actual domain name.
Let's say that our page is www.domain1.com:
var domainName = window.location.host;
var domainNumber = domainName.substr(10, 1);
var finalDomain = (domainNumber+1);
If I print finalDomain on the screen, I got 11. So because of that my redirect is not working.
How do I do domainNumber plus 1, so I got 2 and not 11?
substr method will return you a string, not a number. so you are getting "1" , not 1
when you do "1"+1, you will get "11"
use parseInt() method to convert "1" to 1 before the addition operation.
var finalDomain = parseInt(domainNumber)+1;
domainNumber is a string, not a number, so when you add 1, you're actually concatenating the string "1" onto the end of a string "1" to make "11". You need to convert it into a number using the parseInt() function, as follows:
var domainNumber = parseInt(domainName.substr(10, 1), 10);
Note: The second parameter passed to parseInt() signifies that the string is in decimal (base 10). Now domainNumber is a number rather than a string, so if you try to add one to it you'll get 2.
var finalDomain will be a number, unless you set it to be a string by calling toString():
var finalDomain = (domainNumber + 1).toString() - If you do this, finalDomain will be a string containing the value "2".
Hope this helps.
This function should do the trick parseInt:
Converts a string to an integer.
var finalDomain = parseInt(domainNumber) + 1;
The issue you are having is because in javascript "1" + 1 is "11". So, you need to convert the string "1" to int in order to add it 1 afterwards.
Test it yourself here:
alert("1" + 1 === "11")
alert(1 + 1 === 2)
try this
var domainName = window.location.host;
var domainNumber = domainName.substr(10, 1);
domainNumber = parseInt(domainNumber);
var finalDomain = (domainNumber+1);
u need to parse ur domainNumber variable to integer type in order to do addition.
see here http://www.w3schools.com/jsref/jsref_parseint.asp

get wrong result function jquery javascript

I am using the following script. But I am receiving a wrong result for x_b_bbetrag.
When do an calculation exp 100/108 I get 9.92 instead of 92.59.
What am I missing here?
Code below:
var betrag = 100
var kurs = 1
var minkl= 1
var msatz= 0.08
$("#x_b_betrag").change(function() {
var betrag = $("#x_b_betrag").val();
var kurs = $("#x_b_kurs").val();
var minkl =$("input[name='x_b_mwstinkl']:checked").val();
var msatz =$("input[name='x_b_mwst']:checked").val();
if (minkl == "1"){
$("#x_b_rechenbetrag").val((betrag * kurs).toFixed(2));
$("#x_b_bbetrag").val( ( (betrag * kurs) /(1 + msatz) ).toFixed(2));
}
Use parseFloat
multiplication, division and subtraction automatically parse string to number. for summation you need to parse it.
$("#x_b_bbetrag").val( ( (betrag * kurs) /(1 + parseFloat(msatz) ) ).toFixed(2));
///1 + "1" = 11 not 2
Parse your inputs into numbers.
For example :
var betrag = parseFloat($("#x_b_betrag").val());
MDN on parseFloat
The value of the msatz variable is not 0.08 but "0.08". It's a string, so when you add one to it, the number will be converted to a string so that they can be concatenated, and the result is "10.08" not 1.08. The string will implicitly be converted to a number when you use it in the division, as it's not possible to divide by a string.
Parse the string into a number:
var msatz = parseFloat($("input[name='x_b_mwst']:checked").val());

Adding User input without rounding (Google Apps Script)

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