Limiting floating numbers to 2 decimal places

I use text() to place numbers for result on display: text(num,x,y); Floating point numbers display 3 decimal places by default . Can i limit this so the numbers are 2 decimal places or even 1? Thanks



  • Thanks, but nf() requires a left and right value. I want the right to always be 2 significant digits but could live with the 0 fill for example 23.40 instead of 23.4 but the left number of significant digits changes. If i use 6, it pads 0's in front . example 23.40 becomes 000023.40

    I don't want the leading 0's in the numbers but want to maintain room for a maximum of 6 significant digits.

    In C there is print format statement like 6.2lf for floating point numbers.

    Any equivalent in Processing? or maybe a function to call with number, format info and location.

  • Answer ✓

    Made a function to do it. It works convert to string then use str.indexOf(.) to get number of sig digits to left then nf(strval,strval.indexOf("."),2) to return modified string version of number for text.

  • Answer ✓

    how is this not what you want?

    float f1 = 1.2;
    println(nf(f1, 0, 2)); // 1.20
    float f2 = 1.234;
    println(nf(f2, 0, 2)); // 1.23
    float f3 = 1.0;
    println(nf(f3, 0, 2)); // 1.00
    float f4 = 1234.567;
    println(nf(f4, 0, 2)); // 1234.57 - rounded up
  • Duh. I didn't realize 0 was an acceptable parameter for the left parameter in nf() Thanks

Sign In or Register to comment.