I have a string : "-10.456"
I want to convert it to -10.465 in decimal (using JavaScript) so that I can compare for greater than or lesser than with another decimal number.
Regards.
The parseInt function can be used to parse strings to integers and uses this format: parseInt(string, radix);
Ex: parseInt("-10.465", 10); returns -10
To parse floating point numbers, you use parseFloat, formatted like parseFloat(string)
Ex: parseFloat("-10.465"); returns -10.465
Simply pass it to the Number function:
var num = Number(str);
Here are two simple ways to do this if the variable str = "-10.123":
#1
str = str*1;
#2
str = Number(str);
Both ways now contain a JavaScript number primitive now. Hope this helps!
In javascript, you can compare mixed types. So, this works:
var x = "-10.456";
var y = 5.5;
alert(x < y) // true
alert(x > y) // false
the shortcut is this:
"-3.30" <--- the number in string form
+"-3.30" <----Add plus sign
-3.3 <----- Number in number type.
Related
I am wondering how I can convert 1,000,000 to 1.0E6 in JavaScript.
I'd like the complete opposite of the parseInt function?
Many thanks!
Use toExponential then modify the string as needed:
(1000000).toExponential()
"1e+6"
1000000 and 1.0e6 is identically notation in javascript. Function parseInt(string[, radix])
simply convert string to number by radix.
For back convert number to string you can use intValue.toString(radix)
var x = 1200000;
var val = x.toExponential();
var val = val.replace("+", "");
alert(val);
I have the following JS immbedded in a page:
var round = Math.round;
var id = $(this).attr("id");
var len = id.length;
var indexPos = len -1; // index of the number so that we can split this up and used it as a title
var pasType = id.substring(0, indexPos); // adult, child or infant
var ind = round(id.substring(indexPos)); // converts the string index to an integer
var number = (id.substring(indexPos) + 1); // creates the number that will go in the title
window.alert(number);
id will be something like adult0, and I need to take that string and split it into adult and 0 - this part works fine.
The problem comes in when I try to increment the 0. As you can see I use Math.round to convert it to an integer, and then add 1 to it - I expect 0 to be 1 after this. However, it doesn't seem to be converting it to integer, because I get 01, not 1. When testing this with adult1 the alert I get is 11.
I'm using this question for reference, and have also tried var number += id.substring(indexPos);, which breaks the JS (unexpected identifier '+=')
Does anyone know what I'm doing wrong? Is there a better way of doing this?
The parseInt() function parses a string and returns an integer,10 is the Radix or Base
[DOC]
var number = parseInt(id.substring(indexPos) , 10 ) + 1;
This is to do with JavaScript's + in operator - if a number and a string are "added" up, the number is converted into a string:
0 + 1; //1
'0' + 1; // '01'
To solve this, use the + unary operator, or use parseInt():
+'0' + 1; // 1
parseInt('0', 10) + 1; // 1
The unary + operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt() is self-explanatory (converts into number, ignoring decimal places).
The second argument is necessary for parseInt() to use the correct base when leading 0s are placed:
parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what
There's also parseFloat() if you need to convert decimals in strings to their numeric value - + can do that too but it behaves slightly differently: that's another story though.
Convert by Number Class:-
Eg:
var n = Number("103");
console.log(n+1)
Output: 104
Note:- Number is class. When we pass string, then constructor of Number class will convert it.
JS will think that the 0 is a string, which it actually is, to convert it to a int, use the: parseInt() function, like:
var numberAsInt = parseInt(number, 10);
// Second arg is radix, 10 is decimal.
If the number is not possible to convert to a int, it will return NaN, so I would recommend a check for that too in code used in production or at least if you are not 100% sure of the input.
Although parseInt is the official function to do this, you can achieve the same with this code:
number*1
The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.
Use parseInt():
var number = (parseInt(id.substring(indexPos)) + 1);` // creates the number that will go in the title
If you are sure id.substring(indexPos) is a number, you can do it like so:
var number = Number(id.substring(indexPos)) + 1;
Otherwise I suggest checking if the Number function evaluates correctly.
I am using a function where I have a readonly text input, and when I execute the function I want the number value + 1. So let's say I have 60, when I execute the function, the number returned should be 61.
But instead it's coming out 601, which is just adding the number 1 to the string. Any clue as to what is going on? Subtraction, multiplication and division all work fine. Here is a snippet
var num= $("#originalnum").val() + 1;
$("#originalnum").val(num);
And yes i've tried a few different variations, am I missing something?
A simple unary + is sufficient to turn a string into a number in this case:
var num = +$("#originalnum").val() + 1;
$("#originalnum").val(num);
The problem is that .val() returns the value of the element as a string, and when you use the + operator on a string it does string concatenation. You need to convert the value to a number first:
var num = +$("#originalnum").val() + 1; // unary plus operator
// OR
var num = Number($("#originalnum").val()) + 1; // Number()
// OR
var num= parseFloat($("#originalnum").val()) + 1; // parseFloat()
// OR
var num= parseInt($("#originalnum").val(),10) + 1; // parseInt()
Note that if you use parseInt() you must include the radix (10) as the second parameter or it will (depending on the browser) treat strings with a leading zero as octal and strings with a leading "0x" as hexadecimal. Note also that parseInt() ignores any non-numeric characters at the end of the string, including a full-stop that the user might have intended as a decimal point, so parseInt("123.45aasdf",10) returns 123. Similarly parseFloat() ignores non-numeric characters at the end of the string.
Also if it's a user-entered value you should double-check that it actually is a number and perhaps provide an error message if it isn't.
When you use the *, / or - operators JS tries to convert the string to a number automatically, so that's why those operators "work" (assuming the string can be converted).
You should use the parseInt function and make sure the value is number(use isNaN function):
var val = $("#originalnum").val();
var num = 0;
if ( !isNaN(val) )
num= parseInt(val) + 1;
Use parseInt():
var num= parseInt($("#originalnum").val(),10) + 1;
So your number is treated as an integer instead of a string (as .val() treats the result as string by default)
If you don't like the above code spelling, you can try it this way too.
$("#originalnum").val(function() {
$(this).val(parseInt($(this).val()) + 1)
});
I get 28.6813276578 when i multiply 2 numbers a and b, how can i make it whole number with less digits
and also, when i multiply again i get results after first reult like 28.681321405.4428.68 how to get only one result ?
<script>
$(document).ready(function(){
$("#total").hide();
$("#form1").submit(function(){
var a = parseFloat($("#user_price").val());
var b = parseFloat($("#selling").val());
var total = a*b;
$("#total").append(total)
.show('slow')
.css({"background":"yellow","font-size":50})
;
return false;
});
});
</script>
You can do several things:
total = total.toFixed([number of decimals]);
total = Math.round(total);
total = parseInt(total);
toFixed() will round your number to the number of decimals indicated.
Math.round() will round numbers to the nearest integer.
parseInt() will take a string and attempt to parse an integer from it without rounding. parseInt() is a little trickier though, in that it will parse the first characters in a string that are numbers until they are not, meaning parseInt('123g32ksj') will return 123, whereas parseInt('sdjgg123') will return NaN.
For the sake of completeness, parseInt() accepts a second parameter which can be used to express the base you're trying to extract with, meaning that, for instance,
parseInt('A', 16) === 10 if you were trying to parse a hexidecimal.
See Math.round(...).
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/round
In addition to the other answers about rounding, you are appending the answer to "total" by using
$("#total").append(total)
You need to replace the previous text rather than appending by using
$("#total").html(total)
I have a variable
var fval = 4;
now I want out put as 4.00
JavaScript only has a Number type that stores floating point values.
There is no int.
Edit:
If you want to format the number as a string with two digits after the decimal point use:
(4).toFixed(2)
toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.
var fval = 4;
console.log(fval.toFixed(2)); // prints 4.00
var fval = 4;
var fvalfloat = parseFloat(fval).fixed(2)