Shorten large number with javascript
algorithm, javascript, math
Solution
Source: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toExponential
There is a toExponential() in javascript
So if you want to have a total of 11 characters remaining in the exponential representation, you may pass the number of digits remain after the decimal places
`toExponential(5)` may results `2.12122e+67` for your number `21212202382541035306949186015338569645685453497668055588619610488832`
Update: selected a better source from mozilla instead of w3school. Thanks @T.J. Crowder
Update 2: Source:http://www.php.net/manual/en/language.types.float.php
For php, use `round()` seems possibly force a scientific notation conversion on the number.
Problem
I have this large number: 21212202382541035306949186015338569645685453497668055588619610488832 Javascript automatically shortens it for me like this: 2.1212202382540943e+67 But since I put that inside a table cell with a fixed with, I need the number to be less or equal then 11 digits in total. So in example, if I have the previous mentioned number, it should be converted to: ~2.1212e+67 And, if the number is: 128330558031338336 it should show ~1.2833e+17 So basically, if the length of a number is longer then 11 digits, it should start adding the powers of 10 to it and also start rounding the number. How can I do this withing JavaScript? I tried with `substring()`, but I have problems determining the exact powers to be shown. Edit The end script looks like this: ``` if ( num.length > 11 ) { num = parseFloat( num ); var n = '~'+ num.toExponential( 4 ); } else { var n = num; } ``` Thanks a lot Black Maggie