Double value with specific precision in java

Related searches

I'm programming a simple java program. I need to get a string from input and divide it into two parts: 1-double 2-string. Then I need to do a simple calculation on the double and send the result to the output with specific precision(4). It works fine, but there is a problem when the input is 0, then it doesn't work properly.

For example for these input, output will be:

1 kg output:2.2046

3.1 kg output:6.8343

But when the input is 0, the output should be 0.0000, but it shows 0.0 . What should I do to force it to show 0.0000?

I read similar post about double precision, they suggest something like BigDecimal class, but I can't use them in this case, my code for doing this is:

line=input.nextLine();
array=line.split(" ");
value=Double.parseDouble(array[0]);
type=array[1];
value =value*2.2046;
String s = String.format("%.4f", value);
value = Double.parseDouble(s);
System.out.print(value+" kg\n");

DecimalFormat will allow you to define how many digits you want to display. A '0' will force an output of digits even if the value is zero, whereas a '#' will omit zeros.

System.out.print(new DecimalFormat("#0.0000").format(value)+" kg\n"); should to the trick.

See the documentation

Note: if used frequently, for performance reasons you should instantiate the formatter only once and store the reference: final DecimalFormat df = new DecimalFormat("#0.0000");. Then use df.format(value).

How to set Precision for Double values in Java?, In Java, there are few ways to display double in 2 decimal places. JavaDocs � How to round double / float value to 2 decimal points in Java. Use DecimalFormat to format your double value to fixed precision string output. DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits.

add this instance of DecimalFormat to the top of your method:

DecimalFormat four = new DecimalFormat("#0.0000"); // will round and display the number to four decimal places. No more, no less.

// the four zeros after the decimal point above specify how many decimal places to be accurate to.
// the zero to the left of the decimal place above makes it so that numbers that start with "0." will display "0.____" vs just ".____" If you don't want the "0.", replace that 0 to the left of the decimal point with "#"

then, call the instance "four" and pass your double value when displaying:

double value = 0;
System.out.print(four.format(value) + " kg/n"); // displays 0.0000

Java - Display double in 2 decimal places, Learn how to check the primality of the number using Java. private static double round(double value, int places) { Precision.round(PI, 3);� You can't set the precision of a double (or Double) to a specified number of decimal digits, because floating-point values don't have decimal digits. They have binary digits. You will have to convert into a decimal radix, either via BigDecimal or DecimalFormat, depending on what you want to do with the value later.

I suggest you to use the BigDecimal class for calculating with floating point values. You will be able to control the precision of the floating point arithmetic. But back to the topic :)

You could use the following:

static void test(String stringVal) {
    final BigDecimal value = new BigDecimal(stringVal).multiply(new BigDecimal("2.2046"));
    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(4);
    df.setMinimumFractionDigits(4);
    System.out.println(df.format(value) + " kg\n");
}

public static void main(String[] args) {
    test("0");
    test("1");
    test("3.1");
}

will give you the following output:

0,0000 kg

2,2046 kg

6,8343 kg

How to Round a Number to N Decimal Places in Java, represents the total number of digits in unscaled value i.e. for the number 9232.129394, the precision is 4 + 6 = 10. In special case when number� Set scale in Java. There are multiple ways in Java to round the double value to certain scale, as mentioned in the below example, BigDecimal rounding in Java. import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; public class RoundDouble { public double round1(double input, int scale) { BigDecimal bigDecimal = new BigDecimal (input).setScale (scale, RoundingMode.HALF_EVEN); return bigDecimal.doubleValue (); } public double round2(double input) { return

System.out.format("%.4f kg\n", 0.0d) prints '0.0000 kg'

Precision and scale for a Double in java, If precision is one of your requirements, use BigDecimal instead. Let's explore this problem with the help of an example: All floating point values� The BigDecimal class in Java is useful for providing operations such as format conversion, hashing, and rounding operations on floating-point numbers in Java. It is used to handle and perform high precision operations such as arithmetic etc on double numbers in Java. It is usually used in finance applications to handle data.

String.format is just makign a String representation of the floating point value. If it doesnt provide a flag for a minimum precision, then just pad the end of the string with zeros.

Why You Should Never Use Float and Double for Monetary, Last Updated: 04-12-2018 The java.math.BigDecimal.doubleValue () is an in-built function which converts the BigDecimal object to a double. This function converts the BigDecimal to Double.NEGATIVE_INFINITY or Double.POSITIVE_INFINITY as appropriate or according to the passed object, if its magnitude is too big to be represented as a double.

double PI = 3.1415; However, both types should never be used for precise values, such as currencies. For that, and also for rounding, we can use the BigDecimal class. 3. Formatting a Decimal Number

- Java - Display double in 2 decimal places. Hello, Can you share Java code or script for finding P-value of large data sets:-

Because answer will change when you call .doubleValue () in many cases. Example: output of BigDecimal.valueOf (toBeTruncated) .setScale (3, RoundingMode.HALF_UP) is 12.500. then after .doubleValue (), the output will be 12.5 i.e. precision is lost.

Comments
  • Try "%0.4f". That means 'format a floating point value, pad it with zeros until you have 4 digits'.
  • i used "%.4f", but it shows this error: Exception in thread "main" java.util.MissingFormatWidthException: 0.4f
  • See also stackoverflow.com/questions/10959424/… but this is not a duplicate of that because of the formatting wanted for 0.
  • I already did, replace your last line which prints out your value.
  • it worked for me, but please change it to ("#0.0000"), your answer's out put is .0000 , but if we use ("#0.0000") , it show 0.0000, thanks for your help.
  • Thanks for your info, i didn't know how use bigDecimal to set precision.
  • BlackLight's answer looks better.
  • i used your suggestion, but it doesn't work, as you said BlackLight's answer is what i want, Thanks,
  • It's impossible for my answer to "not work" :D It's just adding "0"'s to a string. It is a sub-optimal solution though. No point re-inventing wheels!
  • i think it doesn't work because of this part value=Double.parseDouble(array[0]);
  • @MehrdadSalimi I meant add the padding on the resultant String :) That's what (i presume) decimalformat will be doing internally.
  • your answer and blacklight's answer are what i want, thanks for your help.