Converting string to int/float in jQuery - javascript

I am getting a value from a div :
<div id="test">100</div>
And what I want to do is to get the value with jQuery, raise with 50% and show the value.
$number= $('#test').text() //getting the value, without parseInt or parseFloat?
$newNumber = $number * 0,5 //show the result of this
I often end up with NaN, so I'd like to have a guidance on that. Thank you.

Suppose we have following markups:
<div id="test">100</div>
<div id="result"></div>
what you are looking for can be achieved as following (without using parseInt() or parseFloat() functions)
var number = $('#test').text();
var result = Number(number) + (number * 0.5);
$('#result').html(result);

You have error in your code, just fix it with:
$number * 0.5
Using dot, not comma.

Related

Pure Javascript - Turn number into a %

My program spits out a number between 0 and 1, and I cant change that. I need to turn it into a % to use as a variable for a CSS selector.
<div id="Value">0.50</div>
<script>
var element = document.getElementById("Value");
var percent = element * 100;
</script>
But how am I meant to put a % symbol on the end so I can do this:
document.getElementById("circle").style.marginLeft = percent;
Any help would be appreciated, thank you.
String concatenation:
document.getElementById("circle").style.marginLeft = percent + "%";
Since "%" is a string, percent will get converted to string and then the result will be the percent value followed by "%".
As Federico pointed out, you should be using either .value (if the id="Value" element is a field element [an input, textarea, or select]) or .textContent or .innerHTML (if it's not). In your case, it's a div, so textContent would make sense:
var value = document.getElementById("Value").textContent;
var percent = value * 100; // Implicitly converts `value` to number
document.getElementById("circle").style.marginLeft = percent + "%"; // Implicitly converts `percent` to string
try
circle.style.marginLeft = Value.innerText*100 + '%'
<div id="Value">0.50</div>
<div id="circle">◉<div>
document.getElementById("circle").style.marginLeft = percent + '%';
When used on strings, the + operator is called the concatenation operator.
Reference: Javascript Operators
This should solve it.
document.getElementById("circle").style.marginLeft = percent+"%";
In Javascript you can concat natively an int and a string using the '+' operator which means that -
var a = 5
var b = a + '%'
result is b = '5%'
Use innerHTML to get the text from the element
var element = document.getElementById("Value").innerHTML;
var percent = parseFloat(element)*100;
percent+='%';
console.log(percent)
<div id="Value">0.50</div>

Parsing integers in AngularJS

I am using AngularJS in one of our application.
In the code below, while loading the page the expression addition (number, valuetoadd) parses correctly and give output as 1+1=2 but while changing the input it doesn't parse correctly and it gives output as `1+2=12'.
Where do I need to change?
<div ng-controller='MathsController'>
<input type="range" min="0" max="100" step="1" value="1" ng-model='valuetoadd'/>
<p>Addition table of <b>{{valuetoadd}}</b></p>
<div ng-repeat='number in numbers'>
{{number}} + {{valuetoadd}} = {{ addition(number,valuetoadd) }}
</div>
</div>
<script type="text/javascript">
function MathsController($scope)
{
$scope.valuetoadd= 1;
$scope.numbers =[1,2,3,4,5,6,7,8,9,10];
$scope.addition = function(number,valuetoadd)
{
return number+valuetoadd;
}
}
</script>
May be number beging passed as a string.
Try:
$scope.addition = function(number, multiplier)
{
return + number + multiplier;
}
+ would convert the string into number.
EDIT:
Now, I see that multiplier is passed as string.
So IT has to be converted instead...
Sorry that I did not read the code carefully.
$scope.addition = function(number, multiplier)
{
return number + +multiplier;
}
Thank you #Artur for pointing this out.
Seems like the root of the problem lies here:
https://github.com/angular/angular.js/issues/1189
Also read this SO topic: Two-way binding with range and number input in AngularJS
As a workaround you can use the solutions proposed by thefrontender and tosh shimayama.
It's worth noticing, though, that it is the multiplier who requires parsing to integer, not the number. See my comment to your question.
Another quick fix is to multiply value by 1 before addition. This will force JavaScript to convert value from string to integer.
Example:
{{value*1 + 10}}
You need to coerce the variables into some sort of numeric type (values from HTML inputs are passed as string by default)
$scope.addition = function (number, multiplier) {
return number + parseInt(multiplier, 10);
}

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

How to get numeric value inside <td>

Trying to calculate sum of checked tr's.
var totalqt=0;
totalqt=totalqt + $(this).closest("tr").find("#qt").text();
It gets correct values but doesn't operate with it like digits. for ex, if value was 1 for first td, and 2 for second td, it alerts 12 instead of 1+2. Tried text() and html(). Same result. What's wrong?
totalqt = totalqt + parseInt($(this).closest("tr").find("#qt").text(), 10);
You need to parse the value as a number this will either be using parseInt(val, base) or parseFloat(val, base):
In your example you'd use:
var totalqt=0;
totalqt=totalqt +parseInt( $(this).closest("tr").find("#qt").text(), 10);
You need to parse the string to an int so that you can use it like an int.
var totalqt=0;
totalqt=totalqt + parseInt($(this).closest("tr").find("#qt").text(), 10);
The 10 is because:
The problem is with how parseInt guesses the base of your number. Read
the parseInt spec. Instead of always defaulting to base 10, it tries
to guess, and if the first character is '0' it thinks you want to
parse as an octal number, and if it starts with '0x' it thinks you
want hexadecimal.
text() returns a string. You want a number. Use parseInt:
var totalqt = 0;
totalqt = totalqt + parseInt($(this).closest("tr").find("#qt").text(), 10);

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