How can I create the mathematical number 1e6 in JavaScript? - javascript

How do I create the number 1e6 with JavaScript?
var veryLargeNumber = //1e6

Here are some different ways:
var veryLargeNumber = 1e6;
var veryLargeNumber = 1.0e+06;
var veryLargeNumber = 1000000;
var veryLargeNumber = 0xf4240;
var veryLargeNumber = 03641100;
var veryLargeNumber = Math.pow(10, 6);

It is written the way you wrote it: var notVeryLargeNumber = 1e6.

Like you wrote above:
var veryLargeNumber = 1e6;//Equals to 1*10^6

This works just fine for me
var veryLargeNumber = 1e6;
console.log( veryLargeNumber );
outputs:
1000000
For more information about really "large" numbers within JavaScript, have a look at this question:
What is JavaScript's Max Int? What's the highest Integer value a Number can go to without losing precision?

For the curious, I went on a little learning safari...
Although the E stands for exponent, the notation is usually referred to as (scientific) E notation or (scientific) e notation
...
Because superscripted exponents like 10^7 cannot always be conveniently displayed, the letter E or e is often used to represent "times ten raised to the power of" (which would be written as "× 10n") and is followed by the value of the exponent; in other words, for any two real numbers m and n, the usage of "mEn" would indicate a value of m × 10n.
https://en.wikipedia.org/wiki/Scientific_notation#E_notation
Use exponential notation if number starts with “0.” followed by more than five zeros. Example:
> 0.0000003
3e-7
http://www.2ality.com/2012/03/displaying-numbers.html
Also: How to convert a String containing Scientific Notation to correct Javascript number format
Number("4.874915326E7") //returns 48749153.26

Related

how to convert giant numbers to pure number in JS

how to convert this giant number 7.125693126643573e+26 to pure number in JS without any scientific notation
Chances are, if the number is provided in scientific notation it'll probably be too large to use integers to represent it without integer overflow occurring. Use string functions to break the scientific notation number apart and construct a new string.
const largeNumber = "7.125693126643573E+26"
const [digit, decimal] = largeNumber.toLowerCase().split(".");
const [decimals, power] = decimal.split('e+');
const zerosToFill = power - decimals.length;
const zeros = Array(zerosToFill).fill(0);
const fullNumber = [digit, decimals, ...zeros].join('');
console.log(`${largeNumber} => ${fullNumber}`);
Use .toLocaleString
var a=7.125693126643573E26;
console.log(a.toLocaleString()); `//output -> 712,569,312,664,357,300,000,000,000`
console.log(a.toLocaleString('aa', { useGrouping: false })); `//output -> 712569312664357300000000000`
This will remove grouping also.
But it will make your number a string.
Use the built in function Number
let number=Number("7.125693126643573E26")
you can also convert it using Math
let number=("7.125693126643573e+26")
parts = String(number).toLowerCase().split('e'),
e = parts.pop(),
l = Math.abs(e),
sign = e/l,
coeff_array = parts[0].split('.');
var dec = coeff_array[1];
if(dec) l = l - dec.length;
num = coeff_array.join('') + new Array(l+1).join('0');
alert(num)

Javascript Big Decimal - Nth Root

Recently I run into the well known floating point precision errors of Javascript. Usually I would avoid floating point calculations on the thin client & rather leave it to the back-end.
I started using the big.js library created by Michael Mclaughlin. Though it has a square-root method/function, it does not have a nth-root methods/function nor does the power function support fraction values as arguments.
So I was wondering if anyone using the library has extended it to have such a function or at least use it to calculate accurate nth-root results.
Michael Mclaughlin suggested that I implement such a function similar in structure to the square-root function. However my attempts at understanding the logic proofed my maths-disability, resulting in simple calculations yielding very wrong results.
Using the algorithm on Rosetta Code also yields incorrect results.
So I was wondering if anyone using the library has extended it to have such a function or at least use it to calculate accurate nth-root results.
Here is the code to my last attempt:
P['nthrt'] = P['nthroot'] = function (n, prec)
{
var negate, r,
x = this,
xc = x['c'],
i = x['s'],
e = x['e'];
// Argument defaults
n = n || 2;
prec = prec || 12;
// Zero?
if ( !xc[0] ) {
return new Big(x)
}
// Negative?
negate = ( n % 2 == 1 && i < 0 );
// Estimate.
r = new Big(1); // Initial guess.
for (var i = 0; i < prec; i++) {
r = (ONE.div(n)).times(r.times(n-1).plus(x.div(r.pow(n-1))));
}
if (negate) r['s'] = -1;
return r;
};
It does not even get obvious results correct like the 4th root of 81 = 3, instead it gets 3.00000000xxx
Newton's method only gives an approximation for the root, so 3.0000xxx should be expected. If you know that the answer should be an integer, you can round r down (Newton's method overestimates the root) and check that r^n=x.
You can use big-numbers library to solve your problem. They support sqrt, pow, exp and many other features.
The pow method accept positive, negative, integer and floating point numbers:
var bn = new BigNumber();
var value = bn.of('81');
var xRoot = value.pow(0.25);
console.log('Result: ' + bn.format(xRoot));
You can use Basenumber.js to perform nth root. Documentation here.
E.g.
// Set precision decimals required
Base.setDecimals(25);
let x = Base("1e+10");
console.log(x.root(10).toString());
<script src='https://cdn.jsdelivr.net/gh/AlexSp3/Basenumber.js#main/BaseNumber.min.js'></script>

String Conversion in Javascript (Decimal to Binary)

A newbie here! Wondering why the following conversion fails!
var num = prompt("Enter num");
alert(num.toString(2));
If num input is 32. I get 32 as num alert message too.
try
(+num).toString(2)
,
Number(num).toString(2)
or
parseInt(num, 10).toString(2)
Any of those should work better for you.
The issue is that the toString method of javascript Number objects overrides the toString method of Object objects to accept an optional radix as an argument to provide the functionality you are looking for. The String object does not override Object's toString method, so any arguments passed in are ignored.
For more detailed information about these objects, see the docs at Mozilla:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toString
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String#Methods
or W3 schools:
http://www.w3schools.com/jsref/jsref_tostring_number.asp
http://www.w3schools.com/jsref/jsref_obj_string.asp
With this function you can specify length of the output.
For example decbin(7,4) produces 0111.
function decbin(dec,length){
var out = "";
while(length--)
out += (dec >> length ) & 1;
return out;
}
demo
Here is my solution that does not use parseInt, but rather a method that shows the logic behind the conversion of decimal to binary.
This method prints the bits to the array which you may later print out if you wish:
var number = 156;
var converted = [];
while(number>=1) {
converted.unshift(number%2);
number = Math.floor(number/2);
}
The converted array will now appear like so:
[1,0,0,1,1,1,0,0]
which of course converts back to 156.
/**
Convert a decimal number to binary
**/
var toBinary = function(decNum){
return parseInt(decNum,10).toString(2);
}
/**
Convert a binary number to decimal
**/
var toDecimal = function(binary) {
return parseInt(binary,2).toString(10);
}
Finally use it
var num= prompt("Enter num");
alert(toBinary(num));
Cast it to an integer first. At the moment you're converting a string to it's binary representation.
num = +num;

Opposite of Number.toExponential in JS

I need to get the value of an extremely large number in JavaScript in non-exponential form. Number.toFixed simply returns it in exponential form as a string, which is worse than what I had.
This is what Number.toFixed returns:
>>> x = 1e+31
1e+31
>>> x.toFixed()
"1e+31"
Number.toPrecision also does not work:
>>> x = 1e+31
1e+31
>>> x.toPrecision( 21 )
"9.99999999999999963590e+30"
What I would like is:
>>> x = 1e+31
1e+31
>>> x.toNotExponential()
"10000000000000000000000000000000"
I could write my own parser but I would rather use a native JS method if one exists.
You can use toPrecision with a parameter specifying how many digits you want to display:
x.toPrecision(31)
However, among the browsers I tested, the above code only works on Firefox. According to the ECMAScript specification, the valid range for toPrecision is 1 to 21, and both IE and Chrome throw a RangeError accordingly. This is due to the fact that the floating-point representation used in JavaScript is incapable of actually representing numbers to 31 digits of precision.
Use Number(string)
Example :
var a = Number("1.1e+2");
Return :
a = 110
The answer is there's no such built-in function. I've searched high and low.
Here's the RegExp I use to split the number into sign, coefficient (digits before decimal point), fractional part (digits after decimal point) and exponent:
/^([+-])?(\d+)\.?(\d*)[eE]([+-]?\d+)$/
"Roll your own" is the answer, which you already did.
It's possible to expand JavaScript's exponential output using string functions. Admittedly, what I came up is somewhat cryptic, but it works if the exponent after the e is positive:
var originalNumber = 1e+31;
var splitNumber = originalNumber.toString().split('e');
var result;
if(splitNumber[1]) {
var regexMatch = splitNumber[0].match(/^([^.]+)\.?(.*)$/);
result =
/* integer part */ regexMatch[1] +
/* fractional part */ regexMatch[2] +
/* trailing zeros */ Array(splitNumber[1] - regexMatch[2].length + 1).join('0');
} else result = splitNumber[0];
"10000000000000000000000000000000"?
Hard to believe that anybody would rather look at that than 1.0e+31,
or in html: 1031.
But here's one way, much of it is for negative exponents(fractions):
function longnumberstring(n){
var str, str2= '', data= n.toExponential().replace('.','').split(/e/i);
str= data[0], mag= Number(data[1]);
if(mag>=0 && str.length> mag){
mag+=1;
return str.substring(0, mag)+'.'+str.substring(mag);
}
if(mag<0){
while(++mag) str2+= '0';
return '0.'+str2+str;
}
mag= (mag-str.length)+1;
while(mag> str2.length){
str2+= '0';
}
return str+str2;
}
input: 1e+30
longnumberstring: 1000000000000000000000000000000
to Number: 1e+30
input: 1.456789123456e-30
longnumberstring: 0.000000000000000000000000000001456789123456
to Number: 1.456789123456e-30
input: 1.456789123456e+30
longnumberstring: 1456789123456000000000000000000
to Number: 1.456789123456e+30
input: 1e+80 longnumberstring: 100000000000000000000000000000000000000000000000000000000000000000000000000000000
to Number: 1e+80

How can I round a number in JavaScript? .toFixed() returns a string?

Am I missing something here?
var someNumber = 123.456;
someNumber = someNumber.toFixed(2);
alert(typeof(someNumber));
//alerts string
Why does .toFixed() return a string?
I want to round the number to 2 decimal digits.
Number.prototype.toFixed is a function designed to format a number before printing it out. It's from the family of toString, toExponential and toPrecision.
To round a number, you would do this:
someNumber = 42.008;
someNumber = Math.round( someNumber * 1e2 ) / 1e2;
someNumber === 42.01;
// if you need 3 digits, replace 1e2 with 1e3 etc.
// or just copypaste this function to your code:
function toFixedNumber(num, digits, base){
var pow = Math.pow(base||10, digits);
return Math.round(num*pow) / pow;
}
.
Or if you want a “native-like” function, you can extend the prototype:
Number.prototype.toFixedNumber = function(digits, base){
var pow = Math.pow(base||10, digits);
return Math.round(this*pow) / pow;
}
someNumber = 42.008;
someNumber = someNumber.toFixedNumber(2);
someNumber === 42.01;
//or even hexadecimal
someNumber = 0xAF309/256; //which is af3.09
someNumber = someNumber.toFixedNumber(1, 16);
someNumber.toString(16) === "af3.1";
However, bear in mind that polluting the prototype is considered bad when you're writing a module, as modules shouldn't have any side effects. So, for a module, use the first function.
I've solved this problem by changing this:
someNumber = someNumber.toFixed(2)
...to this:
someNumber = +someNumber.toFixed(2);
However this will convert the number to a string and parse it again, which will have a significant impact on performance. If you care about performance or type safety, check the the other answers as well.
It returns a string because 0.1, and powers thereof (which are used to display decimal fractions), are not representable (at least not with full accuracy) in binary floating-point systems.
For example, 0.1 is really 0.1000000000000000055511151231257827021181583404541015625, and 0.01 is really 0.01000000000000000020816681711721685132943093776702880859375. (Thanks to BigDecimal for proving my point. :-P)
Therefore (absent a decimal floating point or rational number type), outputting it as a string is the only way to get it trimmed to exactly the precision required for display.
Why not use parseFloat?
var someNumber = 123.456;
someNumber = parseFloat(someNumber.toFixed(2));
alert(typeof(someNumber));
//alerts number
I solved it with converting it back to number using JavaScript's Number() function
var x = 2.2873424;
x = Number(x.toFixed(2));
Of course it returns a string. If you wanted to round the numeric variable you'd use Math.round() instead. The point of toFixed is to format the number with a fixed number of decimal places for display to the user.
You can simply use a '+' to convert the result to a number.
var x = 22.032423;
x = +x.toFixed(2); // x = 22.03
May be too late to answer but you can multiple the output with 1 to convert to number again, here is an example.
const x1 = 1211.1212121;
const x2 = x1.toFixed(2)*1;
console.log(typeof(x2));
What would you expect it to return when it's supposed to format a number ? If you have a number you can't pretty much do anything with it because e.g.2 == 2.0 == 2.00 etc. so it has to be a string.
Because its primary use is displaying numbers? If you want to round numbers, use Math.round() with apropriate factors.
To supply an example of why it has to be a string:
If you format 1.toFixed(2) you would get '1.00'.
This is not the same as 1, as 1 does not have 2 decimals.
I know JavaScript isn't exactly a performance language, but chances are you'd get better performance for a rounding if you use something like:
roundedValue = Math.round(value * 100) * 0.01
You should use it like below.
var someNumber: number = 0.000000;
someNumber = Number(someNumber.toFixed(2))
Why not * the result by 1 i.e
someNumber.toFixed(2) * 1
Here's a slightly more functional version of the answer m93a provided.
const toFixedNumber = (toFixTo = 2, base = 10) => num => {
const pow = Math.pow(base, toFixTo)
return +(Math.round(num * pow) / pow)
}
const oneNumber = 10.12323223
const result1 = toFixedNumber(2)(oneNumber) // 10.12
const result2 = toFixedNumber(3)(oneNumber) // 10.123
// or using pipeline-operator
const result3 = oneNumber |> toFixedNumber(2) // 10.12
For others like me that happen upon this very old question, a modern solution:
const roundValue = (num, decimals = 2) => {
let scaling = 10 ** decimals;
return Math.round((num + Number.EPSILON) * scaling) / scaling;
}
ref: https://stackoverflow.com/a/11832950
Be careful using toFixed() and Math.round(), they can produce unexpected results due to the floating point number system:
function toFixedNumber(num, digits, base){
var pow = Math.pow(base||10, digits);
return Math.round(num*pow) / pow;
}
console.log(toFixedNumber(130.795, 2, 10));
// 130.79 (incorrect)
console.log(toFixedNumber(100.795, 2, 10));
// 100.8
console.log(+130.795.toFixed(2));
// 130.79 (incorrect)
console.log(+100.795.toFixed(2));
// 100.8
I recommend using Lodash's _.round() function: https://lodash.com/docs/4.17.15#round
_.round(130.795, 2);
// 130.8

Categories

Resources