Fraction length

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

should all return length of 3:
5.234
5.23400
5.234000

Any programming language accepted

[EDIT]

Not homework, I want to display fractions at least. For example, I defined a numeric (18.8) in the database. If the user entered only 5.234, the data stored in the database is 5.23400000. I just want to display it only as 5.234

+2
source share
6 answers
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

A little more elegant

+2
source

Given that you are concerned about the mapping, not the internal representation, why not just split 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";

, .

+3

:

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

v > 1, ln() - , int() . v == 1 ln (v) 0, .

(v - int(v)), .

0

. , p > 7 8 ( float32)

0

Java JDBC ResultSet.getBigDecimal(). , (Java 5 , Java 1.4 , - "0.0" ):

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

Java 1.4 . .

0

Java:

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

I assume that you can convert the string anyway.

0
source

All Articles