i am learning to program mobile aplications on Android. My first app is a unit converter. Everithing is working for now, but i have a question about formating numbers. I hava this code to get text from buttons and to convert the appropriet output:
if (bPrevodZ.getText() == "milimeter"){
if (bPrevodDo.getText()=="kilometer"){
String PomocnaPremenna = jednotkaZ.getText().toString();
double cisloNaPrevod = Double.parseDouble(PomocnaPremenna);
cisloNaPrevod = cisloNaPrevod*0.0000001;
vysledok.setText(Double.toString(cisloNaPrevod));
}
The final result is "cisloNaPrevod", but i have problems to show a good format of that number. For example:
12345 mm = 0,0012345 km this is good right ? :)
but if i convert:
563287 mm = 0.05632869999999995 this is bad :) i need it to show 0.0563287
Thx for any help
Use String.format:
String.format("%.6f", cisloNaPrevod);
If you want your number to always have 6 significant figures, use
vysledok.setText(String.format("%.6g", cisloNaPrevod));
giving the result 0.0563287.
If you want to round to 6 numbers after the decimal place, use
vysledok.setText(String.format("%.6f", cisloNaPrevod));
giving the result 0.056329.
Here's some good resources that cover number formatting:
Floating-point cheat sheet for Java
java.util.Formatter
If it's something you're going to do often, perhaps you should use DecimalFormat.
DecimalFormat df = new DecimalFormat("#.#######");
Then call:
df.format(someDoubleValue);
Related
Hi i have an output as "1.234567E6" and similar. Now i want my output to be converted to 1234567. Could you please suggest how to acheive this? Splitting is one way but then E6 part handling i am not sure.
Also the output will be varying in nature, sometimes it would be 6 decimal places , sometimes 10
You can use Double.valueOf then get the long value
long val = Double.valueOf("1.234567E6").longValue();
Or use BigDecimal with longValueExact() to avoid rounding error
long val = new BigDecimal("1.234567E10").longValueExact();
Note: longValueExact() throws Arithmetic Exception if there is any fractional part of this BigDecimal.
You can check the demo here
Use DecimalFormat, it's consistent and clear approach:
DecimalFormat decimalFormat = new DecimalFormat("0");
System.out.println( decimalFormat.format( 1.234567E6 ) );
In String case:
System.out.println( decimalFormat.format( Double.parseDouble("1.234567E6") ) );
Output in both cases
1234567
See code in action: http://tpcg.io/9DsB3GRH
I am developing unit conversion application and need to make decimal formatting proper for different exponential values.
Suppose if answer is 1e-6 answer should be 0.000001
Suppose if answer is 2.1345e3 answer should be 2134.5
Suppose if answer is 2.13456e-9 answer should stay 2.13456e-9
Suppose if answer is 1987.345e-3 answer should be 1.98734e-6
I have attached iphone and android decimal formatting images.
ios and android number formatting
As you can see in android formatting is same for all the values, but i need different formatting for different values.
Please let me know if need more information. Following is my code for formatting in android, all the values are in double only.
DecimalFormat df = new DecimalFormat("######.#####E+0");
String answer = df.format(value);
return answer;
Thanks,
As you want different formats for different sizes you can divide the continuum into different areas and match each area to its format. For example (I am not sure if patterns make any sense, but the idea is simple enough):
public String myFormat(double value) {
String pattern;
if (value > 1) {
pattern = "######.#E+0";
} else if (value > 0.01) {
pattern = "#.#####E+3";
} else {
pattern = "######.#####E+0";
}
return new DecimalFormat(pattern).format(value);
}
I am using dojo, and i read this framework uses the Java NumberFormat pattern.
My question is:how to maintain the values of slider with fractions, and not the division. For example, 1/3 and not 0.333333333. This is because, in future i need to invert 1/3 to 3/1.
So the issue is, how maintain the value in fraction.
var theSlider = new dijit.form.HorizontalSlider({
value:5,
onChange: function(){
console.log(arguments);
},
name:"input"+[i],
slideDuration:0,
onChange:function(val){ dojo.byId('value'+[i]).value = dojo.number.format(1/val,{places:4})},
minimum:1,
maximum:9,
discreteValues:9,
style:{width:"400px"}
},node);
I'd say you want to create your own fraction class or find one on the web like:
http://www.dreamincode.net/forums/topic/87241-fraction-class-that-does-the-4-main-calculation-functions/
simply:
onChange:function(val){ dojo.byId('value'+[i]).value = "1/" + val;},
Solved, thanks
Having problem getting a Longitude/Latitude into the correct format for an api we don't have access to.
We need to convert this to a string and at the moment we have: 4.30044549E7
as the raw form but we need to convert it into 4.30044549 or similar (without Scientific Notation)
If we use
NumberFormat f = new DecimalFormat("#.#######");
f.format(4.30044549E7);
we get: 43004454.9
if we use
Double.toString(4.30044549E7);
we get: "4.30044549E7"
if we try to convert to an int we also get 43004454.9
Can anyone help? I can't find an acceptable solution to get rid of scientific notation on the number
If you really asked what I think you did, you could simply divide the number by 10 until you reach the format you wanted.
double value = 4.30044549E7;
while(value > 10 || value < -10){
value /= 10;
}
System.out.println(String.format("%.8f", value)); //4.30044549
Have you tried format?
String.format("%.10f",doubleValue);
It will format your number with 10 digits after dot.
1e-5 -> 0.000010000
1e5 -> 100000.0000000000
you never can "format" 4.30044549E7 into 4.30044549 because they are not the same.
4.30044549E7 is in fact 43004454.9 so wanting a formatter to display that double as 4.30044549 is an odd question
float per = (num / (float)totbrwdbksint) * 100;
i m getting the value of per as say 29.475342 . i want it to round off upto two decimal places only.like 29.48 .how to achieve this?
You should do this as part of the formatting - the floating point number itself doesn't have any concept of "two decimal places".
For example, you can use a DecimalFormat with a pattern of "#0.00":
import java.text.*;
public class Test
{
public static void main(String[] args)
{
float y = 12.34567f;
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(y));
}
}
As Jon implies, format for display. The most succinct way to do this is probably using the String class.
float f = 70.9999999f;
String toTwoDecPlaces = String.format("%.2f", f);
This will result in the string "71.00"
If you need to control how rounding is done you should check BigDecimal ist has several rounding modes. http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html
You need to be careful here, this answer is not related to java, it relates to all aspects of decimals in many programming languages hence it is generic. The danger lies with rounding numbers, is this, and it has happened in my experience and know that it can be tricky to deal with:
Supposing you are dealing with prices on items, the pricing you get from a retail supplier may be different to the price the computer tells you, sure it is marginally small, but it could add up to big money.
Adding a sales tax on a price can either be positive or negative, it can impact the operating margin of the profit/loss balance sheets...
If you are in this kind of arena of development, then my advice is not to adjust by rounding up/down...it may not show up on small sales of the items, but it could show up elsewhere...an accountant would spot it...Best thing to do is to simply, truncate it,
e.g. 29.475342 -> 29.47 and leave it at that, why?, the .005 can add up to big profit/loss.
In conjunction to what is discussed here...electronic tills and registers use their own variety of handling this scenario, instead of dealing with XX.XXXXXXXXXX (like computers, which has 27/28 decimal places), it deals with XX.XX.
Its something to keep in mind...
Hope this helps,
Best regards,
Tom.
you can use the formatted print method System.out.printf to do the formatted printing if that's what you need