tags:

views:

274

answers:

6
+2  Q: 

Fraction length

How to get the fraction length? If at all possible, without using string operation or loop

should all return length of 3:
5.234
5.23400
5.234000

Any programming language is accepted

[EDIT]

Not a homework, I want to display fractions at its minimum. Example, I defined numeric(18,8) in database. If the user entered only 5.234, the data saved in database is 5.23400000. I just want to display it back as 5.234 only

A: 

For the non-fraction part, the length is:

int((ln(v)/ln(10))+.999)

as long as v > 1 where ln() is the natural logarithm and int() always rounds down. For v == 1, ln(v) returns 0, so you must handle this in a special case.

It ought to be possible to achieve the same thing for the fraction part (v - int(v)) but my math fails me.

Aaron Digulla
A: 

Just implement the division algorithm. And you stop when the number count > 7 or 8 digits (for float32)

+2  A: 

Given that you're concerned about display and not internal representation, why not just strip the trailing 0s?

#!/use/bin/perl

my @nums = ( '5.234', '5.23400', '5.234000' );
$_ =~ s/0+$// for @nums;  # remove trailing 0s
$_ =~ s/\.$// for @nums;  # remove trailing .

print "@nums\n";

You can probably optimize both into a single regex.

codelogic
A: 

When using Java and JDBC, get the value via ResultSet.getBigDecimal(). To get the correct scale, use this code (Java 5 and up; there is a bug in Java 1.4 which makes it fail for "0.0"):

int precision = v.stripTrailingZeros().scale();

For Java 1.4, see this page.

Aaron Digulla
+2  A: 
If Int(num) = num Then Return 0
num *= 10
If Int(num) = num Then Return 1
num *= 10
If Int(num) = num Then Return 2
num *= 10
If Int(num) = num Then Return 3
num *= 10
If Int(num) = num Then Return 4
num *= 10
If Int(num) = num Then Return 5
num *= 10
If Int(num) = num Then Return 6
num *= 10
If Int(num) = num Then Return 7
num *= 10
If Int(num) = num Then Return 8
Throw New Exception("Number exceeds expected precision")

No string operations, no loops.

EDIT:

BTW, to do this with a loop:

result = 0
Do While (Int(num) !> num) 
    num *= 10
    result += 1
Loop
Return result

Slightly more elegant

Patrick McDonald
This one is good. I'm about to settle on repeated dividing(I give up the idea of loop-less) solution and counting 'til 0, but cannot do it since fraction is what I am after, not the whole number. This is a good logic!
Hao
A: 

In Java:

Double.valueOf("5.34000").toString();

I assume, you may want to convert the string to double anyway.