Get Two digit after decimal point in Android or Java

Try this:-

private static String getDecimalFormat(double value) {

    String getValue = String.valueOf(value).split("[.]")[1];

      if (getValue.length() == 1) {
          return String.valueOf(value).split("[.]")[0] +
                "."+ getValue.substring(0, 1) + 
                String.format("%0"+1+"d", 0);
       } else {
          return String.valueOf(value).split("[.]")[0]
            +"." + getValue.substring(0, 2);
      }


 }



Outputs:-
 
System.out.println("value getDecimalFormat:- " + getDecimalFormat(1.0));
value getDecimalFormat:- 1.00

System.out.println("value getDecimalFormat:- " + getDecimalFormat(0.1234567891));
value getDecimalFormat:- 0.12

System.out.println("value getDecimalFormat:- " + getDecimalFormat(-44.0));
value getDecimalFormat:- -44.00

System.out.println("value getDecimalFormat:- " + getDecimalFormat(4500000.963852741));
value getDecimalFormat:- 4500000.96

Comments

Popular posts from this blog

Android Studio 3.5 or above usb device not detected in Android Studio or Unable to detect adb version, exit value: 0xc0000135. ADB depends on the Windows Universal C Runtime, which is usually installed by default via Windows Update. You may need to manually fetch and install the runtime package here: https://support.microsoft.com/en-ca/help/2999226/update-for-universal-c-runtime-in-windows

Lint found fatal errors while assembling a release target.

ViewModelProviders.of(this) is deprecated what to use instead ViewModelProviders.of(this) OR if you don't want to use ViewmodelFactory OR ViewModelProviders error.