开发者

Double datatype formatting

开发者 https://www.devze.com 2023-02-09 02:56 出处:网络
This is a very trivial problem for you guys. Please suggest me the way to achieve the optimal solution. My requirement is, I have an incoming Double value, so if the value after the decimal point is 0

This is a very trivial problem for you guys. Please suggest me the way to achieve the optimal solution. My requirement is, I have an incoming Double value, so if the value after the decimal point is 0, than truncate everything after the decimal. For example: 30.0 should become 30, whe开发者_如何学编程re as 30.12 or 30.1 should stay as it is. Till now I have only figured out a way to know how many digits are there after the decimal point.

package com.convertdatatypes;
public class DoubleCheck {

 public static void main(String args[]){

     Double value = 30.153;
     String val = value.toString(); 
     String[] result = new String[2];

     for(int i=0; i<val.length(); i++){
     result = val.split("\\.");  
     System.out.println("Number of Decimals in: " + val + " : " + result[1].length());
     }
 }

}


use java's DecimalFormat with the following pattern:

0.##

See http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html


Another approach is to use the following

double value = 30.153;
Object value2 = value == (long) value ? String.valueOf((long) value) : value;
System.out.println("Number of Decimals in: " + value2);

This way it prints as a long if the value is unchanged or a double otherwise.

0

精彩评论

暂无评论...
验证码 换一张
取 消