Format float To String - Java java.lang

Java examples for java.lang:float

Description

Format float To String

Demo Code


//package com.java2s;
import java.text.DecimalFormat;

public class Main {
    public static void main(String[] argv) throws Exception {
        float val = 2.45678f;
        int width = 2;
        System.out.println(floatToString(val, width));
    }//from www  . j a va 2 s  . c  o  m

    static DecimalFormat mDF = new DecimalFormat("0.0000");
    static String mSpaces = "                                ";

    public static String floatToString(float val, int width) {
        String str = mDF.format(val);
        if (str.length() >= width) {
            return str;
        }
        return mSpaces.substring(0, width - str.length()) + str;
    }
}

Related Tutorials