Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / How do you round to 1 decimal place in Javascript?

How do you round to 1 decimal place in Javascript?

August 23, 2021 by James Palmer

Math.round(num * 10) / 10 works, here is an example…
var number = 12.3456789
var rounded = Math.round(number * 10) / 10
// rounded is 12.3

if you want it to have one decimal place, even when that would be a 0, then add…
var fixed = rounded.toFixed(1)
// fixed is always to 1 d.p.
// NOTE: .toFixed() returns a string!

// To convert back to number format
parseFloat(number.toFixed(2))
// 12.34
// but that will not retain any trailing zeros

// So, just make sure it is the last step before output,
// and use a number format during calculations!

EDIT: Add round with precision function…
Using this principle, for reference, here is a handy little round function that takes precision…
function round(value, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(value * multiplier) / multiplier;
}

… usage …
round(12345.6789, 2) // 12345.68
round(12345.6789, 1) // 12345.7

… defaults to round to nearest whole number (precision 0) …
round(12345.6789) // 12346

… and can be used to round to nearest 10 or 100 etc…
round(12345.6789, -1) // 12350
round(12345.6789, -2) // 12300

… and correct handling of negative numbers …
round(-123.45, 1) // -123.4
round(123.45, 1) // 123.5

… and can be combined with toFixed to format consistently as string …
round(456.7, 2).toFixed(2) // “456.70”

var number = 123.456;

console.log(number.toFixed(1)); // should round to 123.5

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in