Skip to content

nf() produces problematic string-formatting of very large or small numbers #5710

Open
@golanlevin

Description

@golanlevin

Most appropriate sub-area of p5.js?

  • Accessibility (Web Accessibility)
  • Build tools and processes
  • Color
  • Core/Environment/Rendering
  • Data
  • DOM
  • Events
  • Friendly error system
  • Image
  • IO (Input/Output)
  • Localization
  • Math
  • Unit Testing
  • Typography
  • Utilities
  • WebGL
  • Other (specify if possible)

p5.js version

1.4.1

Web browser and version

Google Chrome 103.0.5060.53 (Official Build) (arm64)

Operating System

MacOS 12.4

Steps to reproduce this

Steps:

  1. Extremely large or small numbers, when formatted with nf(), lose all exponent information. This could be misleading, confusing, or problematic.
  2. For example, I was displaying a variable x which I knew was between 0 and 1, using nf(x,1,2);. Unbeknownst to me, the number was something like 0.000000000001234, for which I would have expected to see something on the screen like 0.00 (because of rounding) — but instead I saw 1.23, which was very confusing. I was concerned that my variable had somehow gone outside the range of 0-1!

Snippet:

Here's some code:

  var smallNum = 1.0 / 700000000.0;
  print("A small number: " + smallNum);
  print("A confusingly-formatted small number: " + nf(smallNum,1,2));
  
  var bigNum = pow(5.0, 123.456);
  print("A big number: " + bigNum); 
  print("A confusingly-formatted big number: " + nf(bigNum,1,2));

This produces the following output:

A small number: 1.4285714285714286e-9 
A confusingly-formatted small number: 1.42 
A big number: 1.9590289562203644e+86 
A confusingly-formatted big number: 1.95 

Recommendation:

Some possible fixes are:

  • Create a new function, nfe() which prints exponent information. This function would be analogous to nfp().
  • And/or have a new function, nfx() output all "extended" information, including the exponent as well as the +/- sign.
  • Or modify nfp() so that it always outputs exponent information, as well as the +/- sign
  • Or output exponent information from nf(), even if it blows out the character count (yuck)
  • Or warn people that all exponent information is discarded (yuck)

In the examples above, I feel the desired result should be the strings 1.42e-9 and 1.95e+86.

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions