number of decimals in float value

edited July 2017 in How To...

Hey guys, I am new to processing so sorry about my basic question : I want to println a float value with four digits after the point but it only show 0.0 in bottom message box. what should I do?

Tagged:

Answers

  • edited July 2017

    https://processing.org/reference/nf_.html

    float num = 4;
    float num2 = 4.25;
    
    println( nf( num, 1, 4 ) );
    println( nf( num2, 1, 4 ) );
    

    4.0000 4.2500

    Keep in mind that nf() returns a String, so you can assign it to a String variable.

  • edited July 2017

    Thank You kalkr, But as you see below the tg variable that I am trying to print with 4 digits is actually used in other lines and it can't be a string. it looks processing rounds the value so other equations wont return true value.

    int   r  =  200;
    float tg;
    
    float xa;
    float ya;
    void setup(){
      size(1000,500);
      background(255);
    smooth();
    }
    void draw(){
      translate(width/2,height/2);
    }
    void mousePressed() {  
      tg =(height/2 - mouseY)/mouseX;
      println(tg);
      strokeWeight(5);
      xa = r/(sqrt(sq((height/2 - mouseY)/mouseX)+1));
      ya = height/2 - ((r*((height/2 - mouseY)/mouseX))/(sqrt(sq((height/2 - mouseY)/mouseX)+1)));
    }
    
  • edited July 2017
    int r = 200; 
    float tg;
    float xa; 
    float ya; 
    
    void setup() { 
      size(1000, 500); 
      background(255); 
      smooth();
    } 
    
    void draw() { 
      translate(width/2, height/2);
    } 
    
    void mousePressed() {
      tg =(height/2 - mouseY)/mouseX; 
    
      /=========
    
      println(tg); //what you had
    
      println( nf(tg, 1, 4) ); //what you want
    
      /=========
    
      strokeWeight(5); 
      xa = r/(sqrt(sq((height/2 - mouseY)/mouseX)+1)); 
      ya = height/2 - ((r*((height/2 - mouseY)/mouseX))/(sqrt(sq((height/2 - mouseY)/mouseX)+1)));
    }
    

    nf() doesnt turn a float variable into a string variable (which isnt possible anyways), it simply formats a number the way you want it to look like and returns it as a string.

Sign In or Register to comment.