Skip to content

Commit

Permalink
Fix decimal numeric with leading zeros (#3898)
Browse files Browse the repository at this point in the history
fix #3888
  • Loading branch information
timotheeguerin committed Jul 18, 2024
1 parent 45bec8e commit 0151b90
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
# Change versionKind to one of: internal, fix, dependencies, feature, deprecation, breaking
changeKind: fix
packages:
- "@typespec/compiler"
---

Fix decimal numeric with leading zeros
5 changes: 3 additions & 2 deletions packages/compiler/src/core/numeric.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,9 @@ function parse(original: string): InternalData {
function stringify(value: InternalData) {
const n = value.n.toString();
const sign = value.s === -1 ? "-" : "";
const decimal = value.e < n.length ? "." + n.slice(value.e) : "";
return sign + n.slice(0, value.e) + decimal;
const int = value.e === 0 ? "0" : n.slice(0, value.e);
const decimal = value.e < n.length ? "." + n.slice(value.e).padStart(value.d, "0") : "";
return sign + int + decimal;
}
const equals = (a: InternalData, b: InternalData) => a.n === b.n && a.e === b.e;

Expand Down
8 changes: 8 additions & 0 deletions packages/compiler/test/core/numeric.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,12 @@ describe("asString", () => {
it("decimals", () => {
expect(Numeric("-123.456").toString()).toEqual("-123.456");
});

it("decimals with leading 0", () => {
expect(Numeric("0.1").toString()).toEqual("0.1");
expect(Numeric("0.01").toString()).toEqual("0.01");
});

it("data with exponent", () => {
expect(Numeric("5e6").toString()).toEqual("5000000");
});
Expand All @@ -186,6 +192,8 @@ describe("asNumber", () => {
it.each([
["0", 0],
["0.0", 0],
["0.1", 0.1],
["0.01", 0.01],
["123", 123],
["123.456", 123.456],
["123.00", 123],
Expand Down

0 comments on commit 0151b90

Please sign in to comment.