user2279603
user2279603

Reputation: 85

Java Formating a string to have a decimal place

I have a military like game and there is a bar at the top that tells the time.(example) when it is 4:06 in the morning it says 4:6 is there a way I can change that to say 04:06 but also say (example) 11:45 and not 011:045.

Here is the time class:

public class Hud {

    public int x, y;
    public int money = 1000;
    public int reputation = 5;
    public int wifi = 3;

    public int time = 0;
    public int timer = 10;
    public int minute = 50;
    public int hour = 10;

    public Hud(int x, int y) {
        this.x = x;
        this.y = y;

    }

    public void tick() {
        if (time >= timer) {
            time = 0;
            minute++;
        } else if (time <= timer) {
            time++;
        }
        if (minute >= 60) {
            minute = 0;
            hour++;
        }
        if (hour >= 24) {
            hour = 0;
        }
    }

    public void render(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        RenderingHints rh = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,       RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
        g2.setRenderingHints(rh);

        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(x, y, Comp.size.width + 9, 20);

        g.setColor(Color.DARK_GRAY);
        g.drawRect(x, y, Comp.size.width + 9, 20);

        // money

        g.setColor(Color.yellow);
        g.setFont(new Font("italic", Font.BOLD, 15));
        g.drawString("€ " + money, 10, 17);

        // reputation

        g.setColor(Color.black);
        g.setFont(new Font("italic", Font.BOLD, 15));
        g.drawString("Rep: " + reputation, 100, 16);

        // time

        g.setColor(Color.black);
        g.setFont(new Font("italic", Font.BOLD, 15));
        g.drawString("" + hour + ":" + minute, Comp.size.width / 2 - 20, 16);

    }
}

Upvotes: 0

Views: 58

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

This has absolutely nothing to do with Font (and so I'm not sure why you mention Font in your question title) and all to do with number formatting. You could do something like:

String displayString = String.format("%02d:%02d", minutes, seconds);

What this does is format the ints found in minutes and seconds into two digit Strings, prepended by a "0" if the int is only one digit long.

The "%02d" are format specifier Strings that help the String.format or java.util.Formatter know how you want to format the number. The % tells the formatter that this is a format specifier. 02 means to make it 2 digits wide and pre-pend a 0 if need b. d means that it's a decimal number.

e.g.,

  g.setColor(Color.black);
  g.setFont(new Font("italic", Font.BOLD, 15));
  String displayString = String.format("%02d:%02d", hour, minute);
  g.drawString(displayString, Comp.size.width / 2 - 20, 16);

Upvotes: 5

Related Questions