Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Java question

Name: Anonymous 2008-02-14 8:16

I was wondering if any of you java geeks could help me with the following:

package testproject;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
      
        doubleClass l = new doubleClass();
       
        while(true)
        {
            l.countUp();
            System.out.println(l.getNumber());
            Scanner in = new Scanner(System.in);
            // wait for <Enter> to be pressed
            in.nextLine();
        }
    }
}

package testproject;
public class doubleClass {

    private double number;
   
    public doubleClass()
    {
        number = 0;
    }
   
    public void countUp()
    {
        number += 0.01;  
    }
   
    public double getNumber()
    {
        return number;
    }
}

So basically a very simple program to test a double.
The problem is that the number fucks up at some points.
e.g. instead of printing 0.06 it prints 0.060000000000000005
Why the fuck is this and how can I get it to work normally
like in c or c++?


Name: Anonymous 2008-02-14 8:41

>>4
That's weird because the following prints it just as I want it:

#include <stdlib.h>
#include <iostream>
#include <string>

double a = 0;

int main(int argc, char** argv) {
   
    while(true)
    {
        a += 0.01;
        std::cout << "The number: "; //+ a << std::endl();
        std::cout << a;
        std::string dummy;
        std::getline(std::cin, dummy);

    }
    return (EXIT_SUCCESS);
}

Perhaps c++ has some built in rounding methods?

But any suggestions as to how I should count a number with 3 decimals in Java?

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List