Fraction length

2019-07-15 13:52发布

问题:

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

回答1:

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



回答2:

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.



回答3:

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.



回答4:

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



回答5:

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.



回答6:

In Java:

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

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