How to Convert Numbers into Scientific Notation

How can I convert numbers into scientific notation?

You can do something like this:

a = 200
a.toExponential(); //output 2e+2

fiddle:
http://jsfiddle.net/Q8avJ/9/

How to avoid scientific notation for large numbers in JavaScript?

There's Number.toFixed, but it uses scientific notation if the number is >= 1e21 and has a maximum precision of 20. Other than that, you can roll your own, but it will be messy.

function toFixed(x) {
if (Math.abs(x) < 1.0) {
var e = parseInt(x.toString().split('e-')[1]);
if (e) {
x *= Math.pow(10,e-1);
x = '0.' + (new Array(e)).join('0') + x.toString().substring(2);
}
} else {
var e = parseInt(x.toString().split('+')[1]);
if (e > 20) {
e -= 20;
x /= Math.pow(10,e);
x += (new Array(e+1)).join('0');
}
}
return x;
}

Above uses cheap-'n'-easy string repetition ((new Array(n+1)).join(str)). You could define String.prototype.repeat using Russian Peasant Multiplication and use that instead.

This answer should only be applied to the context of the question: displaying a large number without using scientific notation. For anything else, you should use a BigInt library, such as BigNumber, Leemon's BigInt, or BigInteger. Going forward, the new native BigInt (note: not Leemon's) should be available; Chromium and browsers based on it (Chrome, the new Edge [v79+], Brave) and Firefox all have support; Safari's support is underway.

Here's how you'd use BigInt for it: BigInt(n).toString()

Example:

const n = 13523563246234613317632;console.log("toFixed (wrong): " + n.toFixed());console.log("BigInt (right):  " + BigInt(n).toString());

PHP - Convert number to scientific notation

You can convert to scientific notation using the %e or %E format specifiers to sprintf/printf.

e The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).

E Like the e specifier but uses uppercase letter (e.g. 1.2E+2). – https://www.php.net/manual/en/function.sprintf.php

To get a certain number of digits after the decimal point, you can use a precision specifier e.g. %.14e

Here's an example from the sprintf manual.

Example #6 sprintf(): scientific notation


<?php $number = 362525200;

echo sprintf("%.3e", $number); ?>

The above example will output:

3.625e+8

How can I convert a JavaScript BigInt value to Scientific Notation?

Intl does support Bigint:

Turns out BigInt.prototype.toLocaleString() can be used with an options for scientific-notation:

const fmt /*: BigIntToLocaleStringOptions */ = {
notation: 'scientific',
maximumFractionDigits: 20 // The default is 3, but 20 is the maximum supported by JS according to MDN.
};

const b1 = 1234567890123456789n;

console.log( b1.toLocaleString( 'en-US', fmt ) ); // "1.234567890123456789E18"


Original answer:

(This code is still useful for JS environments without Intl support or if you need more than 20 digits of precision):

Because bigint values are always integral, and because bigint.toString() will return base-10 digits without further ceremony (other than a leading - for negative values) then then a quick-and-dirty method is to take those rendered digits and insert a radix point (aka decimal dot) after the first digit and tack on the exponent at the end, and because it's a base-10 string the exponent is the same as the length of the rendered string (neat, huh?)

function bigIntToExponential( value: bigint ): string {

if( typeof value !== 'bigint' ) throw new Error( "Argument must be a bigint, but a " + ( typeof value ) + " was supplied." );

//

const isNegative = value < 0;
if( isNegative ) value = -value; // Using the absolute value for the digits.

const str = value.toString();

const exp = str.length - 1;
if( exp == 0 ) return ( isNegative ? "-" : '' ) + str + "e+0";

const mantissaDigits = str.replace( /(0+)$/, '' ); // Remove any mathematically insignificant zeroes.

// Use the single first digit for the integral part of the mantissa, and all following digits for the fractional part (if any).
let mantissa = mantissaDigits.charAt( 0 );
if( mantissaDigits.length > 1 ) {
mantissa += '.' + mantissaDigits.substring( 1 );
}

return ( isNegative ? "-" : '' ) + mantissa + "e+" + exp.toString();
}

console.log( bigIntToExponential( 1n ) ); // "1e+0"
console.log( bigIntToExponential( 10n ) ); // "1e+1"
console.log( bigIntToExponential( 100n ) ); // "1e+2"
console.log( bigIntToExponential( 1000n ) ); // "1e+3"
console.log( bigIntToExponential( 10000n ) ); // "1e+4"
console.log( bigIntToExponential( 1003n ) ); // "1.003e+3"
console.log( bigIntToExponential( 10000000003000000n) ); // "1.0000000003e+16"
console.log( bigIntToExponential( 1234567890123456789n ) ); // "1.234567890123456789e+18"
console.log( bigIntToExponential( 12345678901234567898765432109876543210n ) ); // "1.234567890123456789876543210987654321e+37"

console.log( bigIntToExponential( -1n ) ); // "-1e+0"
console.log( bigIntToExponential( -10n ) ); // "-1e+1"
console.log( bigIntToExponential( -100n ) ); // "-1e+2"
console.log( bigIntToExponential( -1000n ) ); // "-1e+3"

Convert number to scientific notation and obtain exponent

Note that the result can be negative in case the number is less that 1 so we use Math.Floor to handle that:

int exponent = num == 0 ? 0 : (int)Math.Floor((Math.Log10(Math.Abs(num))));

Using format() in R to convert numeric value to scientific notation after rounding

I think rounded_vals might have been stored as character values. Try converting them to numbers using as.numeric() and then put it into the format() function.

Does Haskell have some sort of number conversion to scientific format?

You can make use of the printf :: PrintfType r => String -> r and work with a %e or %E specifier:

Prelude> import Text.Printf
Prelude Text.Printf> printf "%e" 14.25 :: String
"1.425e1"
Prelude Text.Printf> printf "%E" 14.25 :: String
"1.425E1"

here %e specifies the scientific notation with a lowercase e, and the %E with an uppercase E. The output type of printf can be a String, or an IO (). If the String type is used we get a String with the formatted type, for IO () it will print the type to the stdout.


@Noughtmare also mentioned the showEFloat :: RealFloat a => Maybe Int -> a -> String -> String to prepend a string with the exponential representation of a RealFloat number type.


You can also work with a Scientific number, and then work with formatScientific :: FPFormat -> Maybe Int -> Scientific -> String.

If you thus install the scientific package, we can implement this with:

Prelude> import Data.Scientific
Prelude Data.Scientific> formatScientific Exponent Nothing 1000
"1.0e3"

This thus means that the 1000 type should be Scientific not a `

Converting number in scientific notation to int

Behind the scenes a scientific number notation is always represented as a float internally. The reason is the varying number range as an integer only maps to a fixed value range, let's say 2^32 values. The scientific representation is similar to the floating representation with significant and exponent. Further details you can lookup in https://en.wikipedia.org/wiki/Floating_point.

You cannot cast a scientific number representation as string to integer directly.

print int(1e1)  # Works

Works because 1e1 as a number is already a float.

>>> type(1e1)
<type 'float'>

Back to your question: We want to get an integer from float or scientific string. Details: https://docs.python.org/2/reference/lexical_analysis.html#integers

>>> int("13.37")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '13.37'

For float or scientific representations you have to use the intermediate step over float.



Related Topics



Leave a reply



Submit