Softstuff Consulting
My occasional musings of a technical nature
  • Send us a message
  • About Softstuff Consulting
  • Privacy Policy
  • Main Website
JavaScript

Format numbers in Javascript

by Ian Blair December 27, 2019 No Comments

A quick and useful JavaScript function to display numbers with a fixed number of decimal places.

function showAsFloat(num, n) {
     var defaultPlaces = 2;
     return !isNaN(+num) ? (+num).toFixed(n || defaultPlaces) : num;
}

The default number of places can be set by changing the value of the defaultPlaces variable. In the example above it is set to 2 places.

Calling the function showAsFloat(65.267) would return 65.27 

The number of places can be determined when the function is called.

showAsFloat(‘text’,0) will return text so accidental non number scenarios are handled without error.

showAsFloat(65.267,0) will return 65

showAsFloat(65.267,1) will return 65.3

showAsFloat(65.267,2) will return 65.27

Note: The result will be rounded up.

 

javascript

  • Previous Access a Dynamics365 embedded webresource3 years ago
  • Next Throw exceptions in Dynamics365 workflow plugins, or don’t3 years ago

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • How to make your Powershell scripts more annoying
  • What motherboard is in my PC
  • A Dynamics365 plugin thought experiment
  • Registering a Dynamics365 plugin and I get an error
  • Going back in time with Dynamics365

Categories

  • Bootstrap
  • C#
  • CSS
  • Dot Net Core
  • Dynamics365
  • JavaScript
  • Powershell
  • T-SQL
  • Thoughts
  • VBScript
  • Visual Studio
  • Windows
  • Xamarin

Recent Comments

  • S0ftStuffB055 on Call a Dynamics365 workflow from JavaScript
  • Siva on Call a Dynamics365 workflow from JavaScript
  • TC Sharpe on Throw exceptions in Dynamics365 workflow plugins, or don’t
  • BigOwl on Throw exceptions in Dynamics365 workflow plugins, or don’t
  • CRMGod on Access a Dynamics365 embedded webresource

Archives

  • January 2021
  • May 2020
  • March 2020
  • February 2020
  • January 2020
  • December 2019
  • October 2019
  • June 2019
  • May 2019
  • February 2019
2023 Softstuff Consulting. Donna Theme powered by WordPress
  • Twitter