@@ -222,6 +222,9 @@ p5.prototype.matchAll = function(str, reg) {
222
222
* then unused decimal places will be set to 0. For example, calling
223
223
* `nf(123.45, 4, 3)` returns the string `'0123.450'`.
224
224
*
225
+ * When the number is negative, for example, calling `nf(-123.45, 5, 2)`
226
+ * returns the string `'-00123.45'`.
227
+ *
225
228
* @method nf
226
229
* @param {Number|String } num number to format.
227
230
* @param {Integer|String } [left] number of digits to include to the left of
@@ -247,21 +250,24 @@ p5.prototype.matchAll = function(str, reg) {
247
250
*
248
251
* // Display the number as a string.
249
252
* 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);
251
257
*
252
258
* // Display the number with four digits
253
259
* // to the left of the decimal.
254
260
* let left = nf(number, 4);
255
- * text(left, 20, 50 );
261
+ * text(left, 20, 60 );
256
262
*
257
263
* // Display the number with four digits
258
264
* // to the left of the decimal and one
259
265
* // to the right.
260
266
* let right = nf(number, 4, 1);
261
- * text(right, 20, 75 );
267
+ * text(right, 20, 80 );
262
268
*
263
269
* 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.'
265
271
* );
266
272
* }
267
273
* </code>
@@ -295,20 +301,21 @@ p5.prototype.nf = function(nums, left, right) {
295
301
} ;
296
302
297
303
function doNf ( num , left , right ) {
304
+ let isNegative = num < 0 ;
305
+ num = Math . abs ( num ) ;
298
306
let [ leftPart , rightPart ] = num . toString ( ) . split ( '.' ) ;
299
307
308
+
300
309
if ( typeof right === 'undefined' ) {
301
310
leftPart = leftPart . padStart ( left , '0' ) ;
302
- return rightPart ? leftPart + '.' + rightPart : leftPart ;
311
+ let result = rightPart ? leftPart + '.' + rightPart : leftPart ;
312
+ return isNegative ? '-' + result : result ;
303
313
} else {
304
314
let roundedOff = num . toFixed ( right ) ;
305
315
[ leftPart , rightPart ] = roundedOff . toString ( ) . split ( '.' ) ;
306
316
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 ;
312
319
}
313
320
}
314
321
0 commit comments