-1

I want to display an output of float data with 2 decimal places in Java. this is my code

import java.util.*;
import java.math.*;

public class SOAL3{
    public static void main(String args[]){
        int k1;
        float s1, t1, s2, t2;
        float hasil, hasil2;
        Car car, car2;
        Scanner input = new Scanner(System.in);
        int decimalPlaces = 2;
        BigDecimal bd;

        k1 = input.nextInt();
        s1 = input.nextFloat();
        t1 = input.nextFloat();
        car = new Car(k1);
        hasil = car.hitung_kecepatan(s1,t1);

        s2 = input.nextFloat();
        t2 = input.nextFloat();
        car2 = new Car();
        hasil2 = car2.hitung_kecepatan(s2,t2);

        System.out.printf("%.2f",hasil);
        car.print_info();

        System.out.printf("%.2f",hasil2);
        car2.print_info();
    }   
}

abstract class Vehicle{
    protected int jenis;
    protected int jumlah_roda;
    protected int kapasitas_tangki;

    public int getJenis(){
        return jenis;
    }

    public int getJumlah_roda(){
        return jumlah_roda;
    }

    public int getKapasitas_tangki(){
        return kapasitas_tangki;
    }

    public void setJenis(int a){
        this.jenis = a;
    }

    public void setJumlah_roda(int a){
        this.jumlah_roda = a;
    }

    public void setKapasitas_tangki(int a){
        this.kapasitas_tangki= a;
    }

    abstract float hitung_kecepatan(float jarak, float waktu);

    public void print_info(){
        System.out.println(jenis);
        System.out.println(jumlah_roda);
        System.out.println(kapasitas_tangki);
    }
}

class Car extends Vehicle{
    Car() {
        setKapasitas_tangki(200);
        setJenis(1);
        setJumlah_roda(4);
    }

    Car(int a){
        setKapasitas_tangki(a);
        setJenis(1);
        setJumlah_roda(4);
    }

    float hitung_kecepatan(float jarak, float waktu){
        return jarak/waktu;
    }
}

but the result is not valid, what i want is:

  • if the value is 0.75 I wanted to display it to 0.75
  • if the value is 0.5 I wanted to display it to 0.50

but the result i got:

  • 0.75 become 0.751, and
  • 0.5 become 0.501

help me i can't handle it. Thanks..

  • 1
    What does `car.print_info();` print out? Note that `System.out.printf()` doesn't include a newline at the end. – Sizik Oct 05 '15 at 16:45
  • Wow https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=I+want+to+display+an+output+of+float+data+with+2+decimal+places+in+Java. – Peter Lawrey Oct 05 '15 at 16:47

1 Answers1

2
    System.out.printf("%.02f",hasil);
    car.print_info();

    System.out.printf("%.02f",hasil2);
    car2.print_info();
James McLaughlin
  • 18,363
  • 2
  • 45
  • 56