如何有效地将小数点N位置向左移动?

pla*_*etp 6 string perl decimal

我有一堆十进制数字(作为字符串),我从API收到.我需要'缩放'它们,即将它们除以10的幂.这对于整数来说似乎是一个简单的任务,但我有小数,没有保证范围.所以,基本上我需要一个像这样工作的函数:

move_point "12.34" 1; # "1.234"
move_point "12.34" 5; # "0.0001234"
Run Code Online (Sandbox Code Playgroud)

我宁愿不使用浮动来避免任何舍入错误.

Eug*_*ash 7

这有点冗长,但应该做的诀窍:

sub move_point {
    my ($n, $places) = @_;

    die 'negative number of places' if $places < 0;
    return $n if $places == 0;

    my ($i, $f) = split /\./, $n;  # split to integer/fractional parts

    $places += length($f);

    $n = sprintf "%0*s", $places+1, $i.$f;  # left pad with enough zeroes
    substr($n, -$places, 0, '.');  # insert the decimal point
    return $n;
}
Run Code Online (Sandbox Code Playgroud)

演示:

my $n = "12.34";

for my $p (0..5) {
    printf "%d  %s\n", $p, move_point($n, $p);
} 

0  12.34
1  1.234
2  0.1234
3  0.01234
4  0.001234
5  0.0001234
Run Code Online (Sandbox Code Playgroud)