how to convert number to string (without exponent) - javascript

sorry, but i'm not that maths guy, so i do not know how it is really called:
number 12345678901234567890123 could be also stated as 1.2345678901234567890123 * 10^22 (if i'm right and did not miss any decimal...)
consider this javascript:
var number = 12345678901234567890123;
var stringValue = number.toString();
if i do so, it renders the alternative translation (mentioned above). instead i want to render simple, plain, ... 12345678901234567890123
how can this be done?
EDIT:
just to be clear: the number i want to render, does not contain any decimal places. it's just a simple 12345678901234567890123 ... not 12345678901234567890123.123 or anything likewise. and, as i'm with javascript, typeof is number

if you still want to deal with numbers on the order of 10^22 without rounding, then you should use a BigInt class, which implements arbitrary sized numbers. There are several BigInt javascript implementations you can find on the net.

Related

Converting between Bases, and from a String to any Base N in JavaScript (Radix conversion)

First post on here!
I've done a couple hours of research, and I can't seem to find any actual answers to this, though it may be my understanding that's wrong.
I want to convert a string, lets say "Hello 123" into any Base N, lets say N = 32 for simplicity.
My Attempt
Using Javascript's built-in methods (Found through other websites, and):
stringToBase(string, base) {
return parseInt(string, 10).toString(base);
}
So, this encodes the string to base 10 (decimal) and then into the base I want, however the caveat with this is that it only works from 2 to 36, which is good, but not really in the range that I'm looking for.
More
I'm aware that I can use the JS BigInt, but I'm looking to convert with bases as high as 65536 that uses an arbitrary character set that does not stop when encountering ASCII or (yes I'm aware it's completely useless, I'm just having some fun and I'm very persistent). Most solutions I've seen use an alphabet string or array (e.g. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+-").
I've seen a couple threads that say that encoding to a radix which is not divisible by 2 won't work, is that true? Since base 85, 91, exist.
I know that the methods atob() and btoa() exist, but this is only for Radix/Base 64.
Some links:
I had a look at this github page: https://github.com/gliese1337/base-to-base/blob/main/src/index.ts , but it's in typescript and I'm not even sure what's going on.
This one is in JS: https://github.com/adanilo/base128codec/blob/master/b128image.js . It makes a bit more sense than the last one, but the fact there is a whole github page just for Base 128 sort of implies that they're all unique and may not be easily converted.
This is the aim of the last and final base: https://github.com/qntm/base65536 . The output of "Hello World!" for instance, is "驈ꍬ啯𒁗ꍲ噤".
(I can code java much better than JS, so if there is a java solution, please let me know as well)

How to get the number from an input in JavaScript?

I have defined an input in HTML that represents a number. I need to parse the string in JavaScript to a number taking into consideration the different languages that will be entered by the user, for example: '1.34' in English will be written as '1,34' in French. parseFloat('1,344') will be return 1 in case we are in English standard.
You could probably find a library for it, but you can also pretty easily format the numbers into the wanted format yourself.
When you get a number from the input just convert it to string and then use the indexOf() function (http://www.w3schools.com/jsref/jsref_indexof.asp) to see if there's a comma or a dot in the number. It returns the position index of that element in a string so you can then replace with the wanted one to format the number. Position will be -1 if there is no dot/comma.
var num = 32.14;
var string = String(num);
var position = string.indexOf(".");
Hope this helps you.
If it's only those two representations you consider, then another easy solution is to always do
var floatNum = num.replace(/,/g,".");
and then just treat it like any float number.
Unless you really need it for other number systems I'd avoid using a library. Libraries tend to be too big for most projects to utilize properly in my opinion.

Rounding a figure retrieved from html using javascript and jquery

I am having a little problem with rounding numbers which are brought in from html.
For example a value extracted from <input id="salesValue"> using var salesValue = $("salesValue").val() would give me a text value.
So if I did something like var doubleSalesValue = salesValue + salesValue; , it would return the number as a concatenation instead of summation of the two values.
I could use var doubleSalesValue = salesValue * 2.0; which does return the value which is to multiple decimal places. However, if I did want to use the other method, how can I approach the situation.
What methods do you use? I have created a function which I run on each number where I want to restrict the decimal places along with converting the type to number
function round(number, figure){
return Number(Number(number).toFixed(figure));
}
I have to run Number initially to make sure that the value is converted to type number and has the method toFixed, otherwise it would throw an error here. Then I have to round the number again to the number of decimal places as required by the function, and somehow after running the toFixed method the number would sometimes turn to a string.
So, I decided to run the Number function Number(number).toFixed(figure)
Is there anything else or any different paradigm that you follow?
EDIT: I want to know if what I am doing here is conventional or are there better methods for this in general?
If you want to round it to 2 decimals you can simply do this:
var roundedNum = Math.round(parseFloat(originalNum) * 100) / 100;
Regarding your question:
and somehow after running the toFixed method the number would sometimes turn to a string.
I suggest next time read the dox a bit better https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed which says:
Returns
A string representation of number that does not use exponential
notation and has exactly digits digits after the decimal place. The
number is rounded if necessary, and the fractional part is padded with
zeros if necessary so that it has the specified length. If number is
greater than 1e+21, this method simply calls
Number.prototype.toString() and returns a string in exponential
notation.

Is there any drawback with parsing javascript strings to integer implicitly?

What's the difference between
"2" * 1 + 5
and
parseInt("2") + 5
It's just a to write a more readable code, or there are compatibility issues with the first form.
parseInt is used to grab integers from a string. Consider the following code:
var myString = "3 blind mice";
var myInteger = parseInt(myString); //3
JavaScript will do automatic type conversion, so something like this:
"2" * 1 + 5 //7
The string "2" gets converted to a number.
As noted above in the comments, parseInt takes an additional argument for the base.
JavaScript has a lot of very weird rules about type conversion, and sometimes it's not exactly clear what JavaScript will do in every situation. Keep in mind that the + operator is also used for concatenation as well as addition.
If you're trying to explicitly convert something to a number, you can use the Number constructor provided by JavaScript. Considering the following:
var myString = "2";
var myNum = Number(myString); //2
console.log(typeof myNum); //number
Without the new keyword, it can be used to convert strings to numbers. While it does work, I am not sure parseInt should be used for conversion. Just use the Number constructor.
I don't think there are compatibility issues with using coercion in the first form, it is a language feature that should be widely supported.
However, since you have to add code to do the conversion either way (* 1 vs. parseInt), I would vote for parseInt from a style perspective because it makes your intention clearer. It is hard enough sometimes to keep types straight in javascript without using implicit conversions.
Someone not familiar with your code or with javascript might wonder what is going on with that first form as well.
Plus, as indicated in the comments, parseInt is faster so it's a win all around.

Javascript can't render this number correctly: 3494793310847464221

I have an interesting question, I have been doing some work with javascript and a database ID came out as "3494793310847464221", now this is being entered into javascript as a number yet it is using the number as a different value, both when output to an alert and when being passed to another javascript function.
Here is some example code to show the error to its fullest.
<html><head><script language="javascript">alert( 3494793310847464221);
var rar = 3494793310847464221;
alert(rar);
</script></head></html>
This has completly baffeled me and for once google is not my friend...
btw the number is 179 more then the number there...
Your number is larger than the maximum allowed integer value in javascript (2^53). This has previously been covered by What is JavaScript's highest integer value that a Number can go to without losing precision?
In JavaScript, all numbers (even integral ones) are stored as IEEE-754 floating-point numbers. However, FPs have limited "precision" (see the Wikipedia article for more info), so your number isn't able to be represented exactly.
You will need to either store your number as a string or use some other "bignum" approach (unfortunately, I don't know of any JS bignum libraries off the top of my head).
Edit: After doing a little digging, it doesn't seem as if there's been a lot of work done in the way of JavaScript bignum libraries. In fact, the only bignum implementation of any kind that I was able to find is Edward Martin's JavaScript High Precision Calculator.
Use a string instead.
179 more is one way to look at it. Another way is, after the first 16 digits, any further digit is 0. I don't know the details, but it looks like your variable only stores up to 16 digits.
That number exceeds (2^31)-1, and that's the problem; javascript uses 32-bit signed integers (meaning, a range from –2,147,483,648 to 2,147,483,647). Your best choice is to use strings, and create functions to manipulate the strings as numbers.
I wouldn't be all too surprised, if there already was a library that does what you need.
One possible solution is to use a BigInt library such as: http://www.leemon.com/crypto/BigInt.html
This will allow you to store integers of arbitrary precision, but it will not be as fast as standard arithmetic.
Since it's to big to be stored as int, it's converted to float. In JavaScript ther is no explicit integer and float types, there's only universal Number type.
"Can't increment and decrement a string easily..."
Really?
function incr_num(x) {
var lastdigit=Number(x.charAt(x.length-1));
if (lastdigit!=9) return (x.substring(0,x.length-1))+""+(lastdigit+1);
if (x=="9") return "10";
return incr_num(x.substring(0,x.length-1))+"0";
}
function decr_num(x) {
if(x=="0") return "(error: cannot decrement zero)";
var lastdigit=Number(x.charAt(x.length-1));
if (lastdigit!=0) return (x.substring(0,x.length-1))+""+(lastdigit-1);
if (x=="10") return "9"; // delete this line if you like leading zero
return decr_num(x.substring(0,x.length-1))+"9";
}
Just guessing, but perhaps the number is stored as a floating type, and the difference might be because of some rounding error. If that is the case it might work correctly if you use another interpreter (browser, or whatever you are running it in)

Categories