How to reduce textsize of a number (to display entire number) in a textview as it gets longer?

110 views Asked by At

I saw other answers to questions very similar to this one. However, I want the display of my calculator to show normal number till 13 digits and then when 14th digit is added, start showing in scientific notation. Also, I want the size of text to reduce as number of digits crosses 6-digits (just like it is in one of the calculators which I use on phone) eg.

123456 (max text size)

1234567 (text size reduces a unit)

12345678 (text size reduces a unit)

123456789 (text size reduces a unit)

1234567890 (text size reduces a unit)

12345678901 (text size reduces a unit further to fit all digits on the display textview)

1234567890123(text size keeps reducing till 13 digits - this is the minimum text size so no further reduction)

When one more digit is added: 1.2345678901234 × 10^12 (number displayed in scientific notation)

I can't figure out how to change text size when the app is working and also how to display number in scientific notation - only after the number exceeds 13 digits.

Thanks.

1

There are 1 answers

0
Gabe Sechan On BEST ANSWER

I'd create a subclass of TextView called ScientificNotationTextView. Then overwrite the setText function like this:

public void setText(CharSequence text) {
    int length = text.size();
    setTextSize(getSizeForLength(length));
    if(length > 13) {
        NumberFormat formatter = new DecimalFormat("0.#####E0");
        super.setText(formatter.format(text.toString());
    }
    else {
        super.setText(text);
    }
}

Here getSizeForLength should return whatever text size you want to use for that length.