I want to format a double to string with the max length is 7 which contains a dot "." and one digit after it.
For example:
123.4 becomes "00123.4"
12345 becomes "12345.0"
12345.63 becomes "12345.6"
Any help, please!
you can do this:
double test = 33333.327;
String formatted = String.format("%07.1f", test)
System.out.println(formatted);
String.format("%07.1f", myDouble);
See http://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html
Try this -
DecimalFormat df = new DecimalFormat("00000.0");
...
System.out.println(df.format(123.4)); -> 00123.4
System.out.println(df.format(12345)); -> 12345.0
System.out.println(df.format(12345.63)); -> 12345.6
Related
I am attempting to use the DecimalFormat java class for the first time, and I am running into a strange issue. I would like 125.295 to round to 125.30. I would think the format should automatically include the 0, but maybe I'm incorrect.
double num = 125.295;
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.HALF_UP);
String str = df.format(num);
System.out.println(str); //this is yielding 125.3 instead of 125.30
Please help and thank you in advance!
The DecimalFormat class treats '#' as "hide trailing zeroes" or '0' as "show the zeroes". As per the API for DecimalFormat:
0 Number Yes Digit
# Number Yes Digit, zero shows as absent
So you should use DecimalFormat("#.00") instead of DecimalFormat("#.##") if you want it to show trailing zeroes.
Try to use DecimalFormat like this:
double num = 125.295;
DecimalFormat df = new DecimalFormat("###.00");
System.out.println("sum (DecimalFormat) : " + df.format(num));
Output:
125.30
How to set space as thousand separator for DecimalFormat in float? I want to show 13,52 as 13,5, but 13,00 as 13 and I did this with
new DecimalFormat("#.#").format(fIncome)
but I want to 1400,5 be 1 400,5 and 1400 to be 1 400.
For double I use this code (I don't want to shows numbers after comma in dCount):
String.format("%,d", (int)dCount)
But how to use this for floating number with 1 number after comma?
The accepted answer probably lacks a few lines of code, because it doesn't work as described. Here's how I did it:
private static final String DECIMAL_FORMAT = "###,###.#";
private String formatValue(Number value, String formatString) {
DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
formatSymbols.setDecimalSeparator('.');
formatSymbols.setGroupingSeparator(' ');
DecimalFormat formatter = new DecimalFormat(formatString, formatSymbols);
return formatter.format(value);
}
I then call it like this:
formatValue(value, DECIMAL_FORMAT);
To explain how it works, the . in DECIMAL_FORMAT is replaced with decimalSeparator and the , is replaced with groupingSeparator, which is a space in this case.
Ok I got what I want :)
new DecimalFormat("###,###.#").format(fIncome)
I have a function that converst a BigDecimal into a String plus the currency. When I use this the number (e.g. 34) turns into a number with a lot of decimals (e.g. 34.000000).
What can I do to solve this and just show the 34?
Here is my function:
row.put("Money", GcomNullPointerValidator.isNullField(formatUtils.formatCurrency(MoneyDto.getAmount().stripTrailingZeros())));
What is the language? Java?
You can use the split() function of String if you just want to keep numbers before "." :
String mystring = "34.000000";
String correctstring[] = mystring.split(".");
System.out.println(correctstring[0]);
// display : 34
it will delete all digits after "." !
Inside your method that converts a BigDecimal into a String, you can use BigDecimal.setScale() to set the number of digits after the decimal point. For example:
BigDecimal d = new BigDecimal("34.000000");
BigDecimal d1 = d.setScale(2, BigDecimal.ROUND_HALF_UP); // yields 34.00
BigDecimal d2 = d.setScale(0, BigDecimal.ROUND_HALF_UP); // yields 34
You can use this:
String number = "150.000";
number.replaceAll("\\.\\d+$", "");
Or you can use this:
number.split(Pattern.quote("."))[0];
I have some number values, and I want to make sure they hold up to 2 digits.
For example:
11.1233 --> 11.12
11.1 --> 11.1
123 --> 123
I have thought of using
String.format("%.2f",11.1233)
This works well for number more than 2 digits, but it will add extra 0 to the other, for example,it will cause the following result:
11.1 --> 11.10
123 --> 123.00
While I do not need the extra 0.
Is there an alternative?
You could use DecimalFormat to suppress the non-significant digits
DecimalFormat format = new DecimalFormat("0.##");
format.setRoundingMode(RoundingMode.FLOOR);
System.out.println(format.format(11.1233));
You could do something like this...
Double num = 11.111;
Double d = Math.Floor(num * 100) / 100
Depends if you want to store the other digits or not.
Try this:
NumberFormat nf = NumberFormat.getInstance();
double a = 11.1233;
double b = 11.1;
double c = 123;
System.out.println(nf.format(Double.parseDouble(String.format("%.2f",a))));
System.out.println(nf.format(Double.parseDouble(String.format("%.2f",b))));
System.out.println(nf.format(Double.parseDouble(String.format("%.2f",c))));
You definitely want to use DecimalFormat.
You could add a function like this to make things easier.
public void decFormat(String format, double num) {
DecimalFormat formatter = new DecimalFormat(format);
formatter.setRoundingMode(RoundingMode.FLOOR);
System.out.println(formatter.format(num));
}
decFormat("#.##", 11.1233); // Outputs: 11.12
decFormat("#.##", 11.1); // Outputs: 11.1
decFormat("#.##", 11); // Outputs: 11
I'd like to change float like this way:
10.5000 -> 10.5
10.0000 -> 10
How can I delete all zeros after the decimal point, and change it either float (if there's non-zeros) or int (if there were only zeros)?
Thanks in advance.
Why not try regexp?
new Float(10.25000f).toString().replaceAll("\\.?0*$", "")
Well the trick is that floats and doubles themselves don't really have trailing zeros per se; it's just the way they are printed (or initialized as literals) that might show them. Consider these examples:
Float.toString(10.5000); // => "10.5"
Float.toString(10.0000); // => "10.0"
You can use a DecimalFormat to fix the example of "10.0":
new java.text.DecimalFormat("#").format(10.0); // => "10"
java.math.BigDecimal has a stripTrailingZeros() method, which will achieve what you're looking for.
BigDecimal myDecimal = new BigDecimal(myValue);
myDecimal.stripTrailingZeros();
myValue = myDecimal.floatValue();
This handles it with two different formatters:
double d = 10.5F;
DecimalFormat formatter = new DecimalFormat("0");
DecimalFormat decimalFormatter = new DecimalFormat("0.0");
String s;
if (d % 1L > 0L) s = decimalFormatter.format(d);
else s = formatter.format(d);
System.out.println("s: " + s);
You just need to use format class like following:
new java.text.DecimalFormat("#.#").format(10.50000);
Format your numbers for your output as required. You cannot delete the internal "0" values.
Try using System.out.format
Heres a link which allows c style formatting
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
I had the same issue and find a workaround in the following link:
StackOverFlow - How to nicely format floating numbers to string without unnecessary decimal 0
The answer from JasonD was the one I followed. It's not locale-dependent which was good for my issue and didn't have any problem with long values.
Hope this help.
ADDING CONTENT FROM LINK ABOVE:
public static String fmt(double d) {
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
Produces:
232
0.18
1237875192
4.58
0
1.2345