How can I print Java Instant as a timestamp with fractional seconds like 1558766955.037 ? The precision needed is to 1/1000, as the example shows.
I tried (double) timestamp.getEpochSecond() + (double) timestamp.getNano() / 1000_000_000, but when I convert it to string and print it, it shows 1.558766955037E9.
The result you're seeing is the secientific (e-) notation of the result you wanted to get. In other words, you have the right result, you just need to properly format it when you print it:
Instant timestamp = Instant.now();
double d = (double) timestamp.getEpochSecond() + (double) timestamp.getNano() / 1000_000_000;
System.out.printf("%.2f", d);
As others pointed out it is formatting issue. For your specific format you could use Formatter with Locale that supports dot delimetted fractions :
Instant now = Instant.now();
double val = (double) now.getEpochSecond() + (double) now.getNano() / 1000_000_000;
String value = new Formatter(Locale.US)
.format("%.3f", val)
.toString();
System.out.print(value);
Prints :
1558768149.514
System.out.printf("%.3f", instant.toEpochMilli() / 1000.0) should work.
Related
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);
}
}
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);
}
}
I have a long type value which represents cents in currency. I try to convert it to euros. So, I did the following:
long val = 348;
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.FRANCE);
System.out.println(nf.format(val/100));
I thought the above code will print out 3,48 € but I got 3,00 €. Why?
because val/100 is an Integer operation, so the deciaml part is stripped away. For instane
int i = 1; int result = i / 2; will give you 0
Change to System.out.println(nf.format(((float)val/100)));
To force floating point arithmetic , you can use a double literal 100.0 or float literal 100.0f :
System.out.println(nf.format(val/100.0));
I need a line of code that I can use to get the digits after the decimal place when I execute
the code below:
double results = 1500 / 1000;
txtview.setText("K " + resultsoldk);
I need the results to include the reminder as well.
The problem is that the result of
double results = 1500 / 1000;
is 1.0, not 1.5, because you are doing integer division. Make sure at least one of the numbers is a floating-point number when you do the division. For example:
// By adding .0 you make it a double literal instead of an int literal
double results = 1500.0 / 1000;
You can cast using double like below
double results = (double)1500 / 1000;
Also you can format the result using DecimalFormat
DecimalFormat df = new DecimalFormat("0.00##");
String formattedResult=df.format(results);
You can use the String.format(...) method to format the String like this:
txtview.setText(String.format("K %f", resultsoldk));
However, this will not work in you case. As you are dividing two integers, the result will be an integer (which has no remainder). Afterwards it is converted to a double (because you assign it to a double) but at this point, the precision is already lost. You must at least convert one of the integers to a double before you divide them:
double results = (double)1500 / 1000;
or, if you use constants
double results = 1500.0 / 1000;
or
double results = 1500 / 1000.0;
or even
double results = 1500.0 / 1000.0;
String strResult = Double.toString(d);
strResult = strResult.replaceAll("\\d?\\.", "");
Don't know if I get it, but if what you want is the digits after the dot, then you can use this regex.
I'm using this to get current timestamp in seconds and add it to a string Double.toString((System.currentTimeMillis()/1000))
However instead of decimal notation I get "1.23213E9". How do I switch to the decimal notation ?
The shortest is
String secs = "" + System.currentTimeMillis() / 1000;
If you want to retain milli-seconds you can use
String secs = String.format("%.3f", System.currentTimeMillis() / 1000.0);
produces a String like
1342604140.503
Try this:
TimeUnit.MILLISECONDS.toSeconds(((System.currentTimeMillis());
String.valueOf(System.currentTimeMillis() / 1000)
that should do the trick? No need to convert it to a double
If you need to deal with a Double you could do something like this:
double myNum = 1.23213E9;
String myString = NumberFormat.getInstance().format(myNum);
System.out.print(myString);