@@ -222,6 +222,9 @@ p5.prototype.matchAll = function(str, reg) {
222222 * then unused decimal places will be set to 0. For example, calling
223223 * `nf(123.45, 4, 3)` returns the string `'0123.450'`.
224224 *
225+ * When the number is negative, for example, calling `nf(-123.45, 5, 2)`
226+ * returns the string `'-00123.45'`.
227+ *
225228 * @method nf
226229 * @param {Number|String } num number to format.
227230 * @param {Integer|String } [left] number of digits to include to the left of
@@ -247,21 +250,24 @@ p5.prototype.matchAll = function(str, reg) {
247250 *
248251 * // Display the number as a string.
249252 * let formatted = nf(number);
250- * text(formatted, 20, 25);
253+ * text(formatted, 20, 20);
254+ *
255+ * let negative = nf(-number, 4, 2);
256+ * text(negative, 20, 40);
251257 *
252258 * // Display the number with four digits
253259 * // to the left of the decimal.
254260 * let left = nf(number, 4);
255- * text(left, 20, 50 );
261+ * text(left, 20, 60 );
256262 *
257263 * // Display the number with four digits
258264 * // to the left of the decimal and one
259265 * // to the right.
260266 * let right = nf(number, 4, 1);
261- * text(right, 20, 75 );
267+ * text(right, 20, 80 );
262268 *
263269 * describe(
264- * 'The numbers "123.45", "0123.45", and "0123.5" written on three separate lines. The text is in black on a gray background.'
270+ * 'The numbers "123.45", "- 0123.45", "0123.45", and "0123.5" written on four separate lines. The text is in black on a gray background.'
265271 * );
266272 * }
267273 * </code>
@@ -295,20 +301,21 @@ p5.prototype.nf = function(nums, left, right) {
295301} ;
296302
297303function doNf ( num , left , right ) {
304+ let isNegative = num < 0 ;
305+ num = Math . abs ( num ) ;
298306 let [ leftPart , rightPart ] = num . toString ( ) . split ( '.' ) ;
299307
308+
300309 if ( typeof right === 'undefined' ) {
301310 leftPart = leftPart . padStart ( left , '0' ) ;
302- return rightPart ? leftPart + '.' + rightPart : leftPart ;
311+ let result = rightPart ? leftPart + '.' + rightPart : leftPart ;
312+ return isNegative ? '-' + result : result ;
303313 } else {
304314 let roundedOff = num . toFixed ( right ) ;
305315 [ leftPart , rightPart ] = roundedOff . toString ( ) . split ( '.' ) ;
306316 leftPart = leftPart . padStart ( left , '0' ) ;
307- if ( typeof rightPart === 'undefined' ) {
308- return leftPart ;
309- } else {
310- return leftPart + '.' + rightPart ;
311- }
317+ let result = typeof rightPart === 'undefined' ? leftPart : leftPart + '.' + rightPart ;
318+ return isNegative ? '-' + result : result ;
312319 }
313320}
314321
0 commit comments