Skip to content

ExprDecimalPlaces #7953

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: dev/feature
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/main/java/ch/njol/skript/expressions/ExprDecimalPlaces.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package ch.njol.skript.expressions;

import ch.njol.skript.doc.Description;
import ch.njol.skript.doc.Example;
import ch.njol.skript.doc.Name;
import ch.njol.skript.doc.Since;
import ch.njol.skript.expressions.base.SimplePropertyExpression;
import ch.njol.util.Math2;
import org.jetbrains.annotations.Nullable;

@Name("Number of Decimal Places")
@Description("Gets the number of decimal places in a number.")
@Example("""
set {_decimalPlaces} to the number of decimal places of 1.23456789
# {_decimalPlaces} = 8
""")
@Since("INSERT VERSION")
public class ExprDecimalPlaces extends SimplePropertyExpression<Number, Long> {

static {
register(ExprDecimalPlaces.class, Long.class, "number of decimal places", "numbers");
}

@Override
public @Nullable Long convert(Number number) {
if (!(number instanceof Double doubleValue))
return null;
String[] split = doubleValue.toString().split("\\.");
if (split.length != 2)
return null;
return Math2.fit(0, split[1].length(), Long.MAX_VALUE);
}

@Override
public Class<Long> getReturnType() {
return Long.class;
}

@Override
protected String getPropertyName() {
return "number of decimal places";
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
test "decimal places":
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

needs tests for floating point error stuff like places of 0.3/0.1

assert (the number of decimal places of 1.234) is 3 with "Should return 3 decimal places"
assert (the number of decimal places of 1.23456789) is 8 with "Should return 8 decimal places"
assert (the number of decimal places of 1.000000000000001) is 15 with "Should return 15 decimal places
assert (the number of decimal places of 1.0000000000) is not set with "Should return null for trailing zeros"
assert (the number of decimal places of 1) is not set with "Should return null for no decimal number"