Name

nf()

Description

Utility function for formatting numbers into strings. There are two versions: one for formatting floats, and one for formatting ints. The values for the digits and right parameters should always be positive integers. The left parameter should be positive or 0. If it is zero, only the right side is formatted.

As shown in the above example, nf() is used to add zeros to the left and/or right of a number. This is typically for aligning a list of numbers. To remove digits from a floating-point number, use the int(), ceil(), floor(), or round() functions.

Examples

  • int a=200, b=40, c=90;
    String sa = nf(a, 10);
    println(sa);  // Prints "0000000200"
    String sb = nf(b, 5);
    println(sb);  // Prints "00040"
    String sc = nf(c, 3);
    println(sc);  // Prints "090"
    
    float d = 200.94, e = 40.2, f = 9.012;
    String sd = nf(d, 10, 4);
    println(sd);  // Prints "0000000200.9400"
    String se = nf(e, 5, 3);
    println(se);  // Prints "00040.200"
    String sf = nf(f, 3, 5);
    println(sf);  // Prints "009.01200"
    
    String sf2 = nf(f, 0, 5);
    println(sf2);  // Prints "9.01200"
    String sf3 = nf(f, 0, 2);
    println(sf3);  // Prints "9.01"
    

Syntax

  • nf(num)
  • nf(nums)
  • nf(nums, digits)
  • nf(num, digits)
  • nf(nums, left, right)
  • nf(num, left, right)

Parameters

  • nums(int[], float[])the numbers to format
  • digits(int)number of digits to pad with zero
  • num(int, float)the number to format
  • left(int)number of digits to the left of the decimal point
  • right(int)number of digits to the right of the decimal point

Return

  • String[]
Creative Commons License

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.