How to check greater value in javascript? - javascript

There is two value 'a' and 'b'. i need to check a is greater than 'b'
if it is a big value its check the greater values. but here difference only in point values. it ignore point values
var a='20.796';
var b='20.190';
if (parseInt(a) > parseInt(b))
{
alert("function can work");
return false;
}

You parse your numbers as integers. You want rational/real numbers instead. Use parseFloat:
var a = '20.796';
var b = '20.190';
console.log(parseInt(a,10),parseInt(b,10));
console.log(parseFloat(a),parseFloat(b));
Result:
20 20
20.769 20.190
Also, please always use the radix argument if you use parseInt(string [, radix]).
Furthermore - if a and b are numbers, don't save their values in a string. It's much easier to save their values instead:
var a = 20.796;
var b = 20.190;

It's ignoring point values because you are parsing them as integers in the if statement conditional. You have a couple options.
Define the variables as floats instead of strings; remove the parseInt function calls.
Exchange the parseInt for parseFloat calls.

Here, your solution is to parse the strings as floating points rather than integers. For example:
var a = '20.796',
b = '20.190';
if (parseFloat(a) > parseFloat(b)) {
// TODO: .. code ..
}
Your code right now is parsing the strings as integers. Integers are whole number values and CANNOT contain a decimal value, meanwhile floats or floating point numbers CAN contain a decimal value. When you call 'parseInt()' on the floating point, it truncates (or removes) the decimal value and just keeps the whole value. Which is obviously not what you're looking for.
PS: I'm guessing you're new to JavaScript, and so I just want to wish you good luck with learning it. Personnaly, I find JavaScript to be a very beautiful language if you learn it well.

Define your numbers as numbers, and remove the call to parseInt or use parseFloat.
var a=20.796;
var b=20.190;
if (a > b)
{
alert("function can work");
return false;
}
or
if (parseFloat(a) > parseFloat(b))
{
alert("function can work");
return false;
}

Related

Issue with combining large array of numbers into one single number

I am trying to convert an array of numbers into one single number, for example
[1,2,3] to 123.
However, my code can't handle big arrays since it can’t return exact number. Such as
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3] returns 6145390195186705000
Is there any way that I could properly convert into a single number.I would really appreciate any help.
var integer = 0;
var digits = [1,2,3,4]
//combine array of digits into int
digits.forEach((num,index,self) => {
integer += num * Math.pow(10,self.length-index-1)
});
The biggest integer value javacript can hold is +/- 9007199254740991. Note that the bitwise operators and shift operators operate on 32-bit ints, so in that case, the max safe integer is 2^31-1, or 2147483647.
In my opinion, you can choose one of the following:
store the numbers as strings and manipulate them as numbers; you might have to implement special functions to add/subtract/multiply/divide them (these are classic algorithmic problems)
use the BigInt; BigInts are a new numeric primitive in JavaScript that can represent integers with arbitrary precision. With BigInts, you can safely store and operate on large integers even beyond the safe integer limit. Unfortunately, they work only with Chrome right now. If you want to work with other browsers, you might check this or even this if you work with angularjs or nodejs.
Try the following code in the Chrome's console:
let x = BigInt([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3].join(''));
console.log(x);
This will print 6145390195186705543n. The n suffix marks that it is a big integer.
Cheers!
You can use JavaScript Array join() Method and parse it into integer.
Example:
parseInt([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5].join(''))
results:
6145390195186705
Edited: Use BigInt instead of parseInt , but it works only on chrome browser.
The largest number possible in Javascript is
+/- 9007199254740991
Use BigInt. Join all numbers as a string and pass it in BigInt global function to convert it into int
var integer = 0;
var digits = [1,2,3,4]
//combine array of digits into int
digits.forEach((num,index,self) => {
integer += num;
});
integer= BigInt(integer);
Note : Works only on Chrome as of now. You can use othee libraries like BigInteger.js or MathJS

Which javascript function can be used to covert an array of characters into a number?

There are a few Javascript functions available to convert anything into its equivalent number. Number() operates on an Object, valueOf(), parseFloat, parseInt() are also available.
I have an array which stores numbers 0-9 and decimal point, the elements of the array taken together represents a number. What is the best way to convert this array into a number, whole or fractional?
EDIT: Apologies if I were not clear before. The array, holding the 0-9 characters and possibly a decimal point, could represent either a whole number(without the decimal obviously) or a fractional number. So please suggest something that works for both cases. Thanks.
Try this
var a = [1,2,3,".",2,3];
var num = +a.join("");
What is the best way to convert this array into a number, whole or fractional?
Firstly to combine your array elements you should use Array.join().
You will then have a concatenated variable of your values and decimal. To convert this to a whole number, use parseInt(), and to a floating point number use parseFloat(). You can use the unary + operator (which acts similarly to parseFloat), however in my opinion it is not the best choice semantically here, as you seem to want a specific type of number returned.
Example:
var arr = ['1','.','9','1'];
var concat = arr.join();
var whole = parseInt(concat);
var floating = parseFloat(concat);
Also, parseInt will trim the decimal portion of your number, so if you need rounding you can use:
var rounded = Math.round(parseFloat(concat));
You could use the split property of the string. It splits all the characters into an zero based array.
var charSplits = "this is getting split.";
var splitArr = charSplits.split();
Console.log(splitArr);
// this returns i
Console.log(splitArr[2]);

JavaScript treats numbers as strings, not integers, and ParseInt doesn't fix it

I'm trying to insert two numbers in two input type text fields. After I do that, I have to make sure than the first number is smaller than the second. To do this, I'm capturing both fields like this:
var supt = $('#suptotal').val();
var supc = $('#supcubierta').val();
When I compare the two variables, they are strings, so for example 21 is considered bigger than 123.
I've tried to use the function ParseInt, like this
var supt = ParseInt($('#suptotal').val());
but it didn't work. How can I compare the numbers as numbers?
use parseInt($('#suptotal').val(), 10) as against ParseInt($('#suptotal').val(), 10)
The function names are case sensitive
parseInt( $('#suptotal').val(), 10 );
Specify a radix as well, incase the string contains something like '010' which would be interpreted as an octal and result in 8.
ParseInt($('#suptotal').val());
You've written the function incorrectly. parseInt is defined in a lowerCamelCase style.
parseInt($('#suptotal').val());
It is also advised that you specify the radix parameter with 10 for base 10.
parseInt($('#suptotal').val(), 10);
But if you are simply wanting to convert the string into a number, use the unary effect of the binary operator +, which will coerce a value into a number when used on a single operand:
var supt = +$('#suptotal').val();

whole number in javascript?

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)

strip decimal points from variable

I have a series of variables that have a decimal point and a few zeros. How do I strip the variable so it goes from 1.000 to 1?
Simply...
Math.round(quantity);
...assuming you want to round 1.7 to 2. If not, use Math.floor for 1.7 to 1.
use parseInt();
parseInt("1.25");//returns 1
parseInt("1.85");//returns 1
parseInt(1.25);//returns 1
parseInt(1.85);//returns 1
Use number = ~~number
This is the fastest substitute to Math.floor()
parseInt is the slowest method
math.floor is the 2nd slowest method
faster methods not listed here are:
var myInt = 1.85 | 0;
myInt = 1;
var myInt = 1.85 >> 0;
myInt = 1;
Speed tests done here:
http://jsperf.com/math-floor-vs-math-round-vs-parseint/2
Use Math.trunc(). It does exactly what you ask. It strips the decimal.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
For rounding numbers to the nearest Integer you can use Math.round() like so:
Math.round("1.000"); // Will produce 1
Math.round(123.4234); // Will produce 123
You don't need jQuery for this.
You can use parseInt just fine. From the page:
document.write(parseInt("10.33") + "<br />"); // 10
Here's another nice example:
I often use Math.round and toLocateString to convert numbers containing decimal places, into a more readable string, with thousand separators:
var myNumberAsString = "1234567.890123" // "1234567.890123"
var myNumber = Math.round(0.0 + myNumberAsString); // 1234568
return myNumber.toLocaleString(); // "1,234,568"
I find this useful when loading decimal values from, say a JSON Web Service, and need to display them in a friendlier format on a web page (when, of course, I don't need to display all of the decimal places).
A faster, more efficient way would be to use JavaScript's bitwise operators, like so:
function stripDecimals(n) {
return n | 0;
}
// examples:
stripDecimals(23.245); // => 23
stripDecimals(100.015020); // => 100
The | (OR operator) will treat the numbers as 32-bit (binary 0s and 1s), followed by returning the desired result depending on the operands, which in this case would result to an integer stripped of all decimal places.
I suggest you use something called Math.trunc()... put your number in the parentheses. The reason I don't suggest you use Math.round() is that it might change the integer part of your decimal number which some people won't want though you can use Math.round() if you know you want to get the closest integer.

Categories