Number converted in 1e+30 - javascript

How to convert 1e+30 to 1000000000000000000000000000000
I want number as it is entered by User do not convert like 1e+30.
How can achieve this? Is there any way to display actual digits after parse it to float or int?

The core library doesn't give you any support for numbers that don't fit into the native number type, so you'll probably want to use a third party library to help you with large decimals.
For example, https://mikemcl.github.io/decimal.js/
new Decimal('1e+30').toFixed()
// "1000000000000000000000000000000"

You may use toLocaleString
(1000000000000000000000000000000).toLocaleString("en-US", { useGrouping: false })

You can make use of new Array() and String.replace, but it will only be in the form of String
function toNum(n) {
var nStr = (n + "");
if(nStr.indexOf(".") > -1)
nStr = nStr.replace(".","").replace(/\d+$/, function(m){ return --m; });
return nStr.replace(/(\d+)e\+?(\d+)/, function(m, g1, g2){
return g1 + new Array(+g2).join("0") + "0";
})
}
console.log(toNum(1e+30)); // "1000000000000000000000000000000"
Now it's more robust as it doesn't fail even if a really huge number such as 12e100 which will be converted to 1.2e+101, is provided as the . is removed and the last set of digits decremented once. But still 100% accuracy can't be ensured but that is because of limitations of floatation maths in javascript.

Related

How to use .toFixed() (or any alternative) on Nerdamer.solve solutions?

I'm using Nerdamer.solve() to get some linear equation roots. It's working fine but I wonder if there is any way to get only the first 4 decimals of every solution.
EquationSolver.js
//First step, using Nerdamer to solve the equation stored in value
sol_raw = this.nerdamer.solve(value,'x');
xs = this.nerdamer(sol_raw.toString());
//Second step, using Function() in order to evaluate the solutions
solution= Function('return ' + this.nerdamer(xs).evaluate().toString())()
At this point, I'm getting correct results like: 1.74343434. Since I'm rendering the results using Katex, I would like to know where to implement .toFixed(4) or any pseudo way (maybe a Nerdamer method to use n number of decimals on .evaluate()?).
Note.
The result (solution) is a string like [1.74343434, 0.434343, ...] so I could transform it into a float variable and then use .toFixed() but this not an easy solution because the number of roots depends on the equation's grade.
Nerdamer's documentation about evaluate: documentation
#CoronelV,
Another possible approach is to create a toFixed function for formatting the numbers which would take into account real and complex solutions and then calling it on your solutions. Here's a more generalized approach.
var toFixed = function(value, n) {
var img = Number(nerdamer.imagpart(value).text()).toFixed(n);
var real = Number(nerdamer.realpart(value).text()).toFixed(n);
// Format the number assuming i denotes imaginary in your case
var formatted = '';
if(real !== '0.0000') {
formatted += real;
}
if(img !== '0.0000') {
// Put the plus sign betweent the real and imaginary
if(img.charAt(0) !== '-' && formatted) {
formatted += '+';
}
// Assuming you're using i and not j for instance
formatted += img+'i';
}
return formatted;
};
So in your case this would be become something like:
sol_raw = this.nerdamer.solve(value,'x');
xs = this.nerdamer(sol_raw.toString()).each(function(solution) {
roundedSolutions.push(toFixed(solution, 4));
});
this.setState({
solution: roundedSolution.join(''),
equation:value})
This would possibly eliminate the need for your try catch block.
Since the solution is rendered using KaTeX, it's possible rounding the solution via Latex's package, but its even simplest taking the suggestion of #Dj Burb.
Here is my approach:
try {
sol_raw = this.nerdamer.solve(value,'x');
xs = this.nerdamer(sol_raw.toString());
Function('return '+ this.nerdamer(xs).evaluate().toString())().forEach(element => {
roundedSolution.push(element.toFixed(4)) });
} catch (e) {
}
this.setState({
solution: roundedSolution.join(''),
equation:value})
The use of try catch is imperative because while writing the equation, solution.toFixed() returns an error.

How to print an n-bit number with a custom n-length character set in JavaScript without using toString

In the same way we have the hex "number" using the characters 123456789abcdef, and you can simply do integer.toString(16) to go from integer to hex:
> (16).toString(16)
'10'
... I would like to instead use a custom character set, and a custom base. So for hex say I wanted to use the characters 13579acegikmoqsu, then it would be something like this:
> (16).toString(16, '13579acegikmoqsu')
'ik'
I don't actually know what the output value would be in this case, just made that up. But I am looking for how to do this in JavaScript.
Another example outside of hex would be a, for example, base 6 number converted to a string using the character set and123, so it would be something like this:
> (16).toString(6, 'and123')
'a3d'
I don't know what the value is in this case here either, I don't know how to calculate it. Basically wondering how to do this in JavaScript, not necessarily using this toString api, preferably it would be a bit more low-level so I could also understand the logic behind it.
Likewise, it would be helpful to know how to reverse it, so to go from a3d => 16 as in this pseudo-example.
You could map the character values of the integer value as index
function toString(n, characters) {
var radix = characters.length;
return Array
.from(n.toString(radix), v => characters[parseInt(v, radix)])
.join('');
}
console.log(toString(16, '13579acegikmoqsu')); // 31
A version without toString and parseInt.
function toString(n, characters) {
var radix = characters.length,
temp = [];
do {
temp.unshift(n % radix);
n = Math.floor(n / radix);
} while (n)
return temp
.map(i => characters[i])
.join('');
}
console.log(toString(16, '13579acegikmoqsu')); // 31

Parsing toLocaleString and back to float loosing precision

This is what works as expected:
This parseFloat(newValue).toLocaleString("de-DE", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) will result in a String: "34.886,55"
This does not work as expected:
For parseFloat("34.886,55") I get a Number, but I lost everything after the comma: 34.886.
How can I fix this problem ?
I wrote this simple function for doing locale based parseFloat, to the best of my knowledge, the assumptions for this function are.
The decimal operator will come once.
So split it at the decimal("," in our case) to get two elements in an array.
Then remove the thousands separator("." in our case) for each of the elements in the array.
Then joinback the array with the decimal separator ("." in our case)
finally return the parseFloat value of this joined number!
var str = "34.886,55"
console.log("before: ", str);
str = localeParseFloat(str, ",", ".");
console.log("resulting floating value from the function: ", str);
function localeParseFloat(str, decimalChar, separatorChar){
var out = [];
str.split(",").map(function(x){
x = x.replace(".", "");
out.push(x);
})
out = out.join(".");
return parseFloat(out);
}
<script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>
Here's a brief example of the number parsing... Commas are not valid in numbers, only the full stop represents the decimal separator. If it is encountered, the string conversion stop, as you can see on the second log. Also check the third log, I've added a check for the value to be true if it's lower than 100, making it more obvious that you are not playing with thousand separator but really decimal separator.
console.log(parseFloat("34.886.55"));
console.log(parseFloat("34,886.55"));
console.log(parseFloat("34.886,55"), parseFloat("34.886,55") < 100);

Javascript - Format number to always show the original decimal places

I need a js function that show the original count of decimals in a number. For example:
value display
2.31 2
1.0 1
2.3500 4
The problem is that i dont know how get the count of decimals.
I have that code:
value=2.3500;
return CountofDecimals(value); // must be display 4:
Anything help??? Thanks :P
That's not possible. There's no difference between the number 3.5 and 3.50 in JavaScript, or indeed in any other common programming language.
If you actually mean they're strings (value = '2.3500' rather than value = 2.3500) then you can use indexOf:
var decimalPlaces = value.length - value.indexOf('.') - 1;
Caveat: I hate this answer, I don't really advocate it
Don't store it as a number, store it as a string. This can result in "stringly typed" code quickly so it is inadvisable. It is a workaround since JavaScript uses a float as the number type.
Alternatively store it as an Object and parse out the format via a function call:
{ value = "1.2345", decimal = 4}
and use that to create the correct number format. If I had the requirement this is probably the hack I'd use. Or, I would have my server return the formatted string as you can pull that off easily server side.
If it would be possible take these numbers as strings, it definitely is possible..And quite simple actually.
function countDecimals(string){
var delimiters = [",","."];
for(var i = 0; i<delimiters.length; i++){
if(string.indexOf(delimiters[i])==-1) continue;
else{
return string.substring(string.indexOf(delimiters[i])+1).length;
}
}
}
You could use this function:
function decimalplaces(number)
{
numberastring = number.toString(10);
decimalpoint = numberastring.indexOf(".");
if(decimalpoint == -1)
{
return 0;
}
else
{
return numberastring.length - decimalpoint - 1;
}
}

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