p5.js nfp() Function
Last Updated :
22 Aug, 2023
The nfp() function in p5.js is used to format the input numbers (integers or floats) into strings as well as it gives positive (+) and negative (-) sign according to the sign of input numbers.
Syntax:
nfp(Num, Left, Right)
Parameters: This function accepts three parameters as mentioned above and described below:
- Num: This is the input positive number or an array of numbers which are to be formatted.
- Left: This is the positive number which says the number of digits should be on the left side of the decimal point.
- Right: This is the positive number which says the number of digits should be on the right side of the decimal point.
Return Value: It returns the formatted string.
Below programs illustrate the nfp() function in p5.js:
Example 1: This example uses nfp() function to format the input numbers.
function setup() {
createCanvas(450, 200);
}
function draw() {
background(220);
let num1 = 345;
let num2 = -12.3;
let num3 = .5;
let num4 = .05;
let num5 = 0;
let num6 = -0.7;
let A = nfp(num1, 4, 3);
let B = nfp(num2, 4, 2);
let C = nfp(num3, 5, 3);
let D = nfp(num4, 2, 3);
let E = nfp(num5, 2, 2);
let F = nfp(num6, 4, 3);
textSize(16);
fill(color( 'red' ));
text( "Formatted String is: " + A, 50, 30);
text( "Formatted String is: " + B, 50, 60);
text( "Formatted String is: " + C, 50, 90);
text( "Formatted String is: " + D, 50, 110);
text( "Formatted String is: " + E, 50, 140);
text( "Formatted String is: " + F, 50, 170);
}
|
Output:
Example 2: This example uses nfp() function to format the input numbers.
function setup() {
createCanvas(450, 90);
}
function draw() {
background(220);
let num1 = [-345, 0, 2];
let num2 = [-12.3, .4, -2.0];
let A = nfp(num1, 4, 3);
let B = nfp(num2, 4, 2);
textSize(16);
fill(color( 'red' ));
text( "Formatted String is: " + A, 50, 30);
text( "Formatted String is: " + B, 50, 60);
}
|
Output:
Reference: https://p5js.org/reference/#/p5/nfp
Share your thoughts in the comments
Please Login to comment...