开发者

10 digits android

I am Writing a Android calculator and would like to limit the number of charicters that are outputted to 10 eg:

1: ans = 1.23456789101

should show 1.23456789

2: ans = 1234.56789101

开发者_StackOverflow中文版should show 1234.56789

3: ans = 123456789101

should show 1234567890

this is what i have so far but it only works for 1 digit before "."

        ans = (double)Math.round(ans * 100000000) / 100000000;
        String output = String.valueOf(ans);
        if(output.endsWith(".0")){
            output=output.substring(0, output.length()-2);
        }
        textbox.setText(output);

how would i go about doing this


You could do it with a series of if statements about the value, combined with DecimalFormat

if (value >= 10 && value < 100) DecimalFormat formatter = new DecimalFormat("#.#########");
else if (value >= 100 && value < 1000)) DecimalFormat formatter = new DecimalFormat("#.########");
else if (value >= 1000 && value < 10000)) DecimalFormat formatter = new DecimalFormat("#.#######");

etc etc

textBox.setText(String.valueOf(formatter.format(value));

I'm sure there's a more elegant way of handling this, but this would at least work. You can also, for the values over 10 digits, chain in the else if's to include some truncating code.


I would suggest using the DecimalFormat class. It will let you customize the display of your values. Don't hurt yousefl by doing substringing off of the decimal place, my good sir. Also, read up on the rounding behavior to make sure it will do what you want (you provide the DecimalFormat with an unrounded value).

double d = 1234.543534535345345345;
DecimalFormat twoDForm = new DecimalFormat("#.##"); // round to 2 decimals
System.Out.Printline(Double.valueOf(twoDForm.format(d));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜