Format double to percentage - Java java.lang

Java examples for java.lang:double Format

Description

Format double to percentage

Demo Code


//package com.java2s;

import java.text.NumberFormat;

public class Main {
    public static void main(String[] argv) {
        double p1 = 42.45678;
        double p2 = 42.45678;
        System.out.println(percent(p1, p2));
    }/*from  w w  w.  j av a2s. c  o  m*/

    public static String percent(double p1, double p2) {
        if (p2 == 0) {
            return "0.00%";
        }
        String str;
        double p3 = p1 / p2;
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);
        str = nf.format(p3);
        return str;
    }
}

Related Tutorials