How to Set Floating-Point Precision in JavaScript

How to Set Floating-Point Precision in JavaScript

Set Floating-Point Precision in JavaScript

Floating-points in JavaScript have an extremely high precision, and you don't always need this precision. Additionally - your user is even less likely to want it. More often than not - we'll want to "trim" floating-point numbers by setting a specific precision (such as, say, two decimal points) for an end-user.

The Number object has several methods that allow us to change the precision of a floating-point number in JavaScript!

toFixed()

toFixed() is a Number method that is used to convert a number to fixed-point notation (rounding the result where necessary) and returns the value as a string:

number.toFixed([decimalPlaces]);

decimalPlaces is optional, and defines the number of digits that should be present after the decimal place and defaults to 0:

let number = 12345.6789
  
console.log(number.toFixed())       // Returns '12346': note rounding, no fractional part
console.log(number.toFixed(1))      // Returns '12345.7': note rounding
console.log(number.toFixed(6))      // Returns '12345.678900': note added zeros
console.log((1.23e+20).toFixed(3))  // Returns '123000000000000000000.000'

If the floating-point number didn't offer precision up to the fixed point you're formatting to - 0s are added as padding to the end.

toPrecision()

toPrecision() is a Number method that formats a number to a precision string - keeping track of how many total digits (including digits to the left and right of the decimal) to display of a number:

number.toPrecision([significantDigits]);

significantDigits is optional, denoting the number of significant digits to display in the result. If omitted, the method just converts the number to a string.

let number = 5.123456
  
console.log(number.toPrecision())    // logs '5.123456'
console.log(number.toPrecision(5))   // logs '5.1235'
  
number = 0.000123
  
console.log(number.toPrecision())    // logs '0.000123'
console.log(number.toPrecision(5))   // logs '0.00012300'

The returned values are of string type:

console.log(typeof number.toPrecision()) // string

Note: The toPrecision() method will pad the resulting value with 0's if there are not enough significant digits, and it does not change the value of the original number - it returns a new result.

toExponential()

The toExponential() function in JavaScript is used to show a number in exponential notation (sometimes known as scientific notation), even if the number is inside the range where JavaScript ordinarily uses standard notation:

number.toExponential([fractionalDigits]);

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Note: It's worth noting that with sufficiently small and sufficiently large numbers - JavaScript automatically displays them in their exponential notation.

fractionalDigits as an argument is optional, and specifies how many fractional digits are to be displayed in the result. If this argument is missing, the output may contain up to 16 fractional digits, depending on your browser:

let number = 95.3434;
  
console.log(number.toExponential());  // 9.53434e+1
console.log(number.toExponential(4)); // 9.5343e+1
console.log(number.toExponential(2)); // 9.53e+1
console.log(95.3434.toExponential()); // 9.53434e+1

Note: The toExponential() method does not change the value of the original number - it returns a new value to be stored.

Conclusion

In this short tutorial, we've covered the process of setting a precision for floating-point numbers in JavaScript, using the toExponential(), toFixed() and toPrecision() methods of the Number object.

Last Updated: February 22nd, 2022
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

Go Unlimited

  • Access all of our courses and guided projects
  • Master new skills and advance your career
  • Comprehensive lessons and expert guidance
  • Early access to all new courses and content

Sign up today!

$19/mo

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms