i want to format my double value to 2 decimals and then make it "text to speech".
this is my code:
mares = mass * acc;
DecimalFormat df = new DecimalFormat("#.00");
df.format(mares);
String mare = String.format("The force is %f", df);
home.speak(mare,TextToSpeech.QUEUE_FLUSH, null);
but it crashes, i don't know why, i put 5 and 6 and it should multiply them and give me 30.00 or something like that.
when i remove DecimalFormat the result is 30.00000000000000, i just don't like it, too many zeros.
can someone help me please?
Thanks in advance!
Your DecimalFormat is returning the formatted string, but you are ignoring it, and passing it as an argument to String.format, which certainly isn't right.
Assign the return of df.format to a string for further reference:
String mare = df.format(mares);
Or pass the numeric value directly to String.format, with the appropriate format precision specified:
String mare = String.format("The force is %.2f", mares);
Related
I am trying to make a number in a BigDecimal variable match the format of ###.# where no matter what number is passed it will come out as ###.#
For example, if I was passed the number 1 in a BigDecimal variable the method would return 001.0
If I was passed 11.1 as a BigDecimal variable the method would return 011.1
I already have a bit of the code to make the decimal places match
BigDecimal x = new BigDecimal(1);
DecimalFormat df = new DecimalFormat("#.0");
String formatted = df.format(x);
So this would return 1.0 however I cannot figure out how to make the leading zeros appear before converting back to BigDecimal.
Can someone help me out or point me in the right direction?
Thanks everyone
Use a NumberFormat instance, with a Locale which uses the dot as decimal separator.
final BigDecimal x = new BigDecimal("11.1");
final NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(1);
nf.setMinimumIntegerDigits(3);
final String formatted = nf.format(x);
NumberFormat is basically a Factory, so for example in this case the underlying formatter returned by getNumberInstance is a DecimalFormat. I always prefer being abstracted off the real implementation.
You can also decide if you want to display the grouping comma or not.
nf.setGroupingUsed(true); // 123,456.0 - default value is true
nf.setGroupingUsed(false); // 123456.0
Use new DecimalFormat("000.0")
Examples
DecimalFormat df = new DecimalFormat("000.0", DecimalFormatSymbols.getInstance(Locale.US));
System.out.println(df.format(new BigDecimal("1"))); // prints: 001.0
System.out.println(df.format(new BigDecimal("11.1"))); // prints: 011.1
System.out.println(df.format(new BigDecimal("123.456"))); // prints: 123.5
System.out.println(df.format(new BigDecimal(".07"))); // prints: 000.1
System.out.println(df.format(new BigDecimal("123456"))); // prints: 123456.0
You can use the StringUtils of apache.
StringUtils.leftPad(number.toString(), 3, '0');
Where the first argument is the String to format, second argument is the number of to left places to validate, and the last argument is the char for complete.
Reggards.
I have a number as
Double d = 100.000000;
I want to remove the decimal point and print the values as 100000000
(Note I am using java)
It is impossible. double doesn't store zeroes after decimal point so 1.0000 is equal to 1.0.
Hint: you can use BigDecimal for this. It have scale.
I'm afraid 100.000000 does not equal 100000000 and as mentioned by #talex, double doesn't store the zeros after the decimal point.
Your best bet is to use a String and remove the . manually:
String s = "100.000000";
System.out.println(s.replaceAll("\\.", "")); //note '.' needs to be escaped
Output:
100000000
You could parse it as a Double then if necessary.
Format the value using String.format and the remove the separator.
double d = 100.000;
String formatted = String.format(
Locale.US, //Using a Locale US to be sure the decimal separator is a "."
"%5f", //A decimal value with 5decimal
d) //The value to format
.replace(".", ""); //remove the separator
System.out.println(formatted);
100000000
Other examples :
100.000123456 > 100000123
You can see that the value is truncated, it is important to understand that.
Note that I have set the String to have 5 decimal number, but this up to you.
the double does not store the number as 100.0000 it just stored as 100.0 that means any unnecessary zeros on the right will be deleted but if the number was like this 100.01234 u can use this trick
Double d = 100.01245;
String text = Double.toString(d);
text.replace(".","");
d = Double.parseDouble(text);
or u can store the number as sting from the beginning
String text = "100.000000";
d.replace(".","");
double d = Double.parseDouble(text);
I was wondering if there is an existing method to convert a formatted number String to number, such as "123,456.78" to 123456.78
Basically, unlike DecimalFormat function, which turns a double variable to a String following that a given format such as "###,###.##" pattern. I want to implement a reverse of this functionality, which turns a String with "###,###.##" format to a double. Is there APIs to do this?
Thank you.
You should have looked through the documentation for DecimalFormat and its superclass. You would have discovered that it has not only format methods, but also parse methods like this one.
The easiest way to do what you want is:
NumberFormat format = NumberFormat.getInstance();
Number value = format.parse(string);
// If you specifically want a double...
double d = value.doubleValue();
You will have to catch ParseException and deal with it. How you do that depends on what you want to do when your string does not represent a valid numeric value. If it's user input, you may want to ask the user to enter the text again.
Here is a simple way to do this
String number = "20,000,000";
int x = Integer.parseInt(number.replace(",", ""));
System.out.println(x);
You just replace the char's that not belong to a number with "" and then parse it into a primitive.
String number = "20,000,000.56";
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(5);
double x = Double.parseDouble(number.replace(",", ""));
System.out.println(df.format(x));
It is a bit different for a Double cause it will display the exponential output and you'll have to prevent that. The code above does that.
df.format(x)
Returns a String but you can cast it with the Double.parseDouble method
Here's a method using a Regex and the replace method if you have more than one delimiter and you know them all :
Let's say the delimiters here are "-" and ","
double x = Double.parseDouble(number.replace("[-,]", "");
I have a String that represents an amount of money passed from input that will optionally contain a decimal point and trailing zeros. It can look like any of these:
inputA = "123.45"
inputB = "123"
inputC = "123.4"
inputD = ".50"
Is there a way to convert these so that they all have the format 0.00 with at least one digit to the left of the decimal point and exactly two to the right without having to convert to a number object like BigDecimal and then back?
You can use DecimalFormat to achieve formatting.
DecimalFormat format = new DecimalFormat("##0.00");
System.out.println(format.format(10));
Output : 10.00
Tricks:
String formattedDouble=String.format("%.2f", Double.valueOf(strDouble));
And, %.2f will format your double as 1.00, 0.20 or 5.21. Double.valueOf(strDouble) convert your String double into a double.
Good day.
I need to format a number in java.
So far I have this:
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
System.out.println(new Double(df2.format(balance)).doubleValue());
But it prints out this
110.0
121.0
133.1
146.41
161.05
But I need it to be with two digits in fraction part. How do I do it?
You don't have to get double value from formatted string.
Just use formatted string, which is returned from format() method of DecimalFormat.
So your code should be like the following:
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
...
System.out.println(df2.format(balance));
Your original code:
System.out.println(new Double(df2.format(balance)).doubleValue());
What you did in your code is: format the double value to string(which is formatted as you specified in the DecimalFormat instance). Then you convert the formatted string to Double instance and get double value from the object, which is double. And then printed it to console. So the formatted string is gone, and the double value is printed as normal.
"But I need it to be with two digits in fraction part. How do I do it?"
DecimalFormat df2 = new DecimalFormat( );
df2.setMinimumFractionDigits(2);
df2.setMaximumFractionDigits(2);
System.out.println(df2.format(balance));
You could also use the setMinimumFractionDigits method of DecimalFormat
df2.setMinimumFractionDigits(2);
your decimal format is right, but
what you are doing before you print this out is new Double(df2.format(balance)) which create new instant of double, which ignores your formatting.
so if you want to display or log your value df2.format(balance) this should be enough
ie:
System.out.println(df2.format(balance));
Try this pattern for formatting #,###,###,##.##-
DecimalFormat df2 = new DecimalFormat( "#,###,###,##.##" );
System.out.println(df2.format(balance));
This should be sufficient:
DecimalFormat df2 = new DecimalFormat("#,##0.00");
System.out.println(df2.format(balance));
The grouping for separator will follow "the interval between the last one and the end of the integer". So there is no benefit from over-specify. Example from the documentation of DecimalFormat:
The grouping separator is commonly used for thousands, but in some countries it separates ten-thousands. The grouping size is a constant number of digits between the grouping characters, such as 3 for 100,000,000 or 4 for 1,0000,0000. If you supply a pattern with multiple grouping characters, the interval between the last one and the end of the integer is the one that is used. So "#,##,###,####" == "######,####" == "##,####,####".
Another thing is that .format() method already output a String, so there is no point in converting it to double. It will cause Exception to be thrown when balance is more than 1000 (the point when separator comes into effect, and Double class cannot parse the String with separator).