Jump to content

Number Formatting #2

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
9 replies to this topic

#1
dunnkers

dunnkers

    Learning Programmer

  • Members
  • PipPipPip
  • 31 posts
Hello,
I want to change
14201
to
14.2k
using NumberFormat
How can i do this?

#2
dunnkers

dunnkers

    Learning Programmer

  • Members
  • PipPipPip
  • 31 posts
I've a little start:

formatter = new DecimalFormat("#'k'");
s = formatter.format(14201); // 14201k

#3
dunnkers

dunnkers

    Learning Programmer

  • Members
  • PipPipPip
  • 31 posts
bump.. anyone?

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
You could start by looking at it as a string. The length of the string tells you how many characters you need before the new decimal.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#5
dunnkers

dunnkers

    Learning Programmer

  • Members
  • PipPipPip
  • 31 posts
That will result in a long if statement maze.

#6
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Why would it do that? Are you supporting more suffixes than k? It's mostly a little math.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#7
dunnkers

dunnkers

    Learning Programmer

  • Members
  • PipPipPip
  • 31 posts
Can you give me an example please?

#8
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
I don't think you can divide by 1000 to drop the last numbers with the formatting.
A short version would be:

NumberFormat formatter = new DecimalFormat("#0.#k");

System.out.println(formatter.format(14201.0/1000.0));

But you have to do /1000.0 yourself (.0 because it has to be doubles)

What wingedpanther wanted to do would be something like the following i guess:

int number = 12345;

double doubleNumber = number;

doubleNumber /= 100;

doubleNumber = Math.round(doubleNumber);

doubleNumber /= 10;


System.out.println(doubleNumber + "k");


#9
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
I'd convert it to a string first. Then display the first n-3 characters, a decimal, and the last of the n-2 characters, and a "k".
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#10
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
Ah ye, probably even easier :D