I want to keep my trailing zeroes when using DecimalFormat - java

The code below is my attempt to convert my three doubles into a format where they have four decimal places always (because I need to print them with four decimal places for what is meant to be a simple assignment), even if all the numbers after the decimal point in the original double are 0 - as in any whole number. I figured I might be able to use the setMinimumFractionDigits() method to prevent DecimalFormat from eliminating trailing zeroes - but it doesn't do the job: "3.0" still gets printed out instead of what I want: "3.0000". I realise that below my instances of this setMinimumFractionDigits() method are literally doing nothing.
(Numbers whose decimal places aren't all zeroes aren't a problem; the code is working as I want it to for them.)
........ Is there an easy fix? There may be; I don't understand very well the methods I'm using here.
double mean = mean(numbers);
double variance = variance(numbers, mean);
double sd = sd(variance);
DecimalFormat meanFormatted = new DecimalFormat("#.####");
meanFormatted.setMinimumFractionDigits(4);
mean = Double.valueOf(meanFormatted.format(mean));
DecimalFormat varianceFormatted = new DecimalFormat("#.####");
varianceFormatted.setMinimumFractionDigits(4);
variance = Double.valueOf(varianceFormatted.format(variance));
DecimalFormat sdFormatted = new DecimalFormat("#.####");
sdFormatted.setMinimumFractionDigits(4);
sd = Double.valueOf(sdFormatted.format(sd));

see this usage
double d = 12.3;
DecimalFormat meanFormatted = new DecimalFormat("#.0000");
System.out.println (meanFormatted.format (d));

Found a solution:
double mean = mean(numbers);
double variance = variance(numbers, mean);
double sd = sd(variance);
Formatter transform = new Formatter();
Formatter transform1 = new Formatter();
Formatter transform2 = new Formatter();
transform.format("%.4f", mean);
transform1.format("%.4f", variance);
transform2.format("%.4f", sd);
System.out.printf("\nMean = %s\n", transform);
System.out.printf("Variance = %s\n", transform1);
System.out.printf("Standard deviation = %s\n", transform2);

Related

How to allow/restrict textview to display only one number after decimal in Android studio [duplicate]

Can I do it with System.out.print?
You can use the printf method, like so:
System.out.printf("%.2f", val);
In short, the %.2f syntax tells Java to return your variable (val) with 2 decimal places (.2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).
There are other conversion characters you can use besides f:
d: decimal integer
o: octal integer
e: floating-point in scientific notation
You can use DecimalFormat. One way to use it:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));
Another one is to construct it using the #.## format.
I find all formatting options less readable than calling the formatting methods, but that's a matter of preference.
I would suggest using String.format() if you need the value as a String in your code.
For example, you can use String.format() in the following way:
float myFloat = 2.001f;
String formattedString = String.format("%.02f", myFloat);
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
float f = 102.236569f;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f)); // output is 102.24
You may use this quick codes below that changed itself at the end. Add how many zeros as refers to after the point
float y1 = 0.123456789;
DecimalFormat df = new DecimalFormat("#.00");
y1 = Float.valueOf(df.format(y1));
The variable y1 was equals to 0.123456789 before. After the code it turns into 0.12 only.
float floatValue=22.34555f;
System.out.print(String.format("%.2f", floatValue));
Output is 22.35.
If you need 3 decimal points change it to "%.3f".
Many people have mentioned DecimalFormat. But you can also use printf if you have a recent version of Java:
System.out.printf("%1.2f", 3.14159D);
See the docs on the Formatter for more information about the printf format string.
A simple trick is to generate a shorter version of your variable by multiplying it with e.g. 100, rounding it and dividing it by 100.0 again. This way you generate a variable, with 2 decimal places:
double new_variable = Math.round(old_variable*100) / 100.0;
This "cheap trick" was always good enough for me, and works in any language (I am not a Java person, just learning it).
Look at DecimalFormat
Here is an example from the tutorial:
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
If you choose a pattern like "###.##", you will get two decimal places, and I think that the values are rounded up. You will want to look at the link to get the exact format you want (e.g., whether you want trailing zeros)
To print a float up to 2 decimal places in Java:
float f = (float)11/3;
System.out.print(String.format("%.2f",f));
OUTPUT: 3.67
> use %.3f for up to three decimal places.
Below is code how you can display an output of float data with 2 decimal places in Java:
float ratingValue = 52.98929821f;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsFR = Float.valueOf(decimalFormat.format(ratingValue)); // output is 52.98
OK - str to float.
package test;
import java.text.DecimalFormat;
public class TestPtz {
public static void main(String[] args) {
String preset0 = "0.09,0.20,0.09,0.07";
String[] thisto = preset0.split(",");
float a = (Float.valueOf(thisto[0])).floatValue();
System.out.println("[Original]: " + a);
a = (float) (a + 0.01);
// Part 1 - for display / debug
System.out.printf("[Local]: %.2f \n", a);
// Part 2 - when value requires to be send as it is
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
System.out.println("[Remote]: " + df.format(a));
}
}
Output:
run:
[Original]: 0.09
[Local]: 0.10
[Remote]: 0.10
BUILD SUCCESSFUL (total time: 0 seconds)
One issue that had me for an hour or more, on DecimalFormat- It handles double and float inputs differently. Even change of RoundingMode did not help. I am no expert but thought it may help someone like me. Ended up using Math.round instead.
See below:
DecimalFormat df = new DecimalFormat("#.##");
double d = 0.7750;
System.out.println(" Double 0.7750 -> " +Double.valueOf(df.format(d)));
float f = 0.7750f;
System.out.println(" Float 0.7750f -> "+Float.valueOf(df.format(f)));
// change the RoundingMode
df.setRoundingMode(RoundingMode.HALF_UP);
System.out.println(" Rounding Up Double 0.7750 -> " +Double.valueOf(df.format(d)));
System.out.println(" Rounding Up Float 0.7750f -> " +Float.valueOf(df.format(f)));
Output:
Double 0.7750 -> 0.78
Float 0.7750f -> 0.77
Rounding Up Double 0.7750 -> 0.78
Rounding Up Float 0.7750f -> 0.77
public String getDecimalNumber(String number) {
Double d=Double.parseDouble(number);
return String.format("%.5f", d);
}
Take care of NumberFormatException as well
small simple program for demonstration:
import java.io.*;
import java.util.Scanner;
public class twovalues {
public static void main(String args[]) {
float a,b;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Values For Calculation");
a=sc.nextFloat();
b=sc.nextFloat();
float c=a/b;
System.out.printf("%.2f",c);
}
}
Just do String str = System.out.printf("%.2f", val).replace(",", "."); if you want to ensure that independently of the Locale of the user, you will always get / display a "." as decimal separator. This is a must if you don't want to make your program crash if you later do some kind of conversion like float f = Float.parseFloat(str);
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);
}
}

Conditional NumberFormatter?

Is there a way to make a NumberFormatter that does the following:
If the Double is a whole number like 5.0, display "5"
If the Double is a decimal like 5.6, display "5.6"
I know this is an old question but this should do exactly what you asked:
var myNumber:Double = 0.0 // set to 5.0 or 5.6 to see result
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 4
let x = formatter.string(from: NSNumber(value: myNumber)) ?? "$\(myNumber)"
print("x = \(x)")
double someNum = 5.6d;
DecimalFormat df = new DecimalFormat("#.#");
String num = df.format(someNum);
if (num.substring(num.length - 1).equals("0")) {
num = num.substring(0, num.length - 2);
}
System.out.println(num);
The DecimalFormat instance formats the double into a string. The code checks the tenth place of precision, i.e. the first digit to the right of the decimal place, and if it be zero, then it shows only whole numbers. Otherwise, it shows the full precision.

Round Double value and exponential notation (java)

how to round "3.416436417734133 in "3.416436418" (nine positions after point) but also if i have "3.7578845854848E41" it round to "3.7578845855E41"? i'm trying to realyze a calculator..
You can use DecimalFormat, I am not sure about the other numbers but currently you have numbers which have single digit before the decimal point. So, check following example where you can format the double value. Note one more thing that you may need to change format pattern for your use case.
FOR EXAMPLE :
double d = 3.7578845854848E41;
double d2 = 3.416436417734133;
DecimalFormat f = new DecimalFormat("0.#########E0");
System.out.println(f.format(d));
System.out.println(f.format(d2));
OUTPUT :
3.757884585E41
3.416436418E0
//Replace E0 with space as format returns String
EDIT :
Because of your default locale. You can change local like this,
//Change locale
DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.US);
DecimalFormat f = new DecimalFormat("0.#########E0", decimalFormatSymbols);
//And than use decimal format
You may use BigDecimal to add a "scale" to your double value :
Double d = 3.416436417734133;
BigDecimal round = new BigDecimal(d);
round = round.setScale(9, BigDecimal.ROUND_CEILING);
System.out.println(round);
You can use this code.
BigDecimal aDecimal = new BigDecimal(3.416436417734133);
BigDecimal another = aDecimal.setScale(9, aDecimal.ROUND_HALF_UP);
System.out.println("another: " + another);
System.out.println(new BigDecimal(3.7578845854848E41,new
MathContext(11,RoundingMode.CEILING)));

How to always round off upto 2 decimal places in java

I have tried the following code but it is not working in a particular case.
Eg: Suppose, I have a double value=2.5045 and i want it to be rounded off upto two decimal places using the below code.After rounding off, i get the answer as 2.5. But I want the answer to be 2.50 instead. In this case,zero is trimmed off. Is there any way to retain the zero so as to get the desired answer as 2.50 after rounding off.
private static DecimalFormat twoDForm = new DecimalFormat("#.##");
public static double roundTwoDecimals(double amount) {
return Double.valueOf(twoDForm.format(amount));
}
try this pattern
new DecimalFormat("0.00");
but this will change only formatting, double cannot hold number of digits after decimal poin, try BigDecimal
BigDecimal bd = new BigDecimal(2.5045).setScale(2, RoundingMode.HALF_UP);
Look at the documentation for DecimalFormat. For # it says:
Digit, zero shows as absent
0 is probably what you want:
Digit
So what you are looking for is either "0.00" or "#.00" as a format string, depending on whether you want the first digit before the period, to be visible in case the numbers absolute value is smalle than 0.
Try this
DecimalFormat format = new DecimalFormat("#");
format.setMinimumFractionDigits(2);
answer.setText(format.format(data2));
Try This
double d = 4.85999999999;
long l = (int)Math.round(d * 100); // truncates
d = l / 100.0;
You are returning a double. But double or Double are objects representing a number and don't carry any formatting information. Ìf you need to output two decimal places the point to do this is when you convert your double to a String.
use # if you want to ignore 0
new DecimalFormat("###,#0.00").format(d)
There is another way to achieve this . I have already posted answer in post
will just answer again here. As we will require rounding off values many times .
public class RoundingNumbers {
public static void main(String args[]){
double number = 2.5045;
int decimalsToConsider = 2;
BigDecimal bigDecimal = new BigDecimal(number);
BigDecimal roundedWithScale = bigDecimal.setScale(decimalsToConsider, BigDecimal.ROUND_HALF_UP);
System.out.println("Rounded value with setting scale = "+roundedWithScale);
bigDecimal = new BigDecimal(number);
BigDecimal roundedValueWithDivideLogic = bigDecimal.divide(BigDecimal.ONE,decimalsToConsider,BigDecimal.ROUND_HALF_UP);
System.out.println("Rounded value with Dividing by one = "+roundedValueWithDivideLogic);
}
}
Output we will get is
Rounded value with setting scale = 2.50
Rounded value with Dividing by one = 2.50
double kilobytes = 1205.6358;
double newKB = Math.round(kilobytes*100.0)/100.0;
DecimalFormat df = new DecimalFormat("###.##");
System.out.println("kilobytes (DecimalFormat) : " + df.format(kilobytes));
Try this if u are still getting the above problem

Formatting a number with correct decimal scale

I need to format a number with scale of 2 decimal places. The original number may be a whole number or a number with three decimal places. However the result should be formatted to have commas and also two decimal places always regardless of whether the original number is whole number or having decimal places.
When original num = 56565656.342 ==> I need 56,565,656.34
When original num = 56565656 ==> I need 56,565,656.00
When original num = 56565656.7 ==> I need 56,565,656.70
I am using the following code which is formatting the code but its failing to add the two decimal places in the above 2 & 3 cases.
String originalNumber = "56565656.7";
BigDecimal b = new BigDecimal(originalNumber).setScale(2, BigDecimal.ROUND_HALF_UP);
String formattedNumber = NumberFormat.getInstance().format(b);
Please let me know if there is any way to accomplish this in efficeint way.
Thanks in advance.
Take a look at the DecimalFormat class.
Alternatively you can setScale method from the BigDecimal Class.
BigDecimal bg1 = new BigDecimal("56565656.342");
BigDecimal bg2 = new BigDecimal("56565656.00");
BigDecimal bg3 = new BigDecimal("56565656.70");
DecimalFormat df = new DecimalFormat("###,###.00");
System.out.println(df.format(bg1.doubleValue()));
System.out.println(df.format(bg2.doubleValue()));
System.out.println(df.format(bg3.doubleValue()));
System.out.println(bg1.setScale(2, BigDecimal.ROUND_HALF_UP));
System.out.println(bg2.setScale(2, BigDecimal.ROUND_HALF_UP));
System.out.println(bg3.setScale(2, BigDecimal.ROUND_HALF_UP));
Yields:
56,565,656.34
56,565,656.00
56,565,656.70
56565656.34
56565656.00
56565656.70
EDIT: Also forgot to mention: If you are after precision, I would recommend you use the setScale method, using the .doubleValue() method will yield a double which can cause loss of precision.
Just use NumberFormat and specify the fraction digits, and rounding method, to print :
String [] originalNumbers = new String[] {
"56565656.342",
"56565656.7",
"56565656"
};
NumberFormat df = NumberFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
df.setRoundingMode(RoundingMode.HALF_UP);
for (String number : originalNumbers) {
String formattedNumber = df.format(new BigDecimal(number));
System.out.println(formattedNumber);
}
Will print
56,565,656.34
56,565,656.70
56,565,656.00
** Edit **
DecimalFormat df = new DecimalFormat("#,###.00");
Will produce the exact same result with the given code above.
DecimalFormat class would do it for you.... You will have to specify appropriate format.

Categories

Resources