vercel / next.js

The React Framework
https://nextjs.org
MIT License
124.67k stars 26.61k forks source link

Next.js Tutorial Acme Dashboard Edit Invoice error. #64849

Open MarkTravis-Johnson opened 4 months ago

MarkTravis-Johnson commented 4 months ago

Verify canary release

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.4.0: Fri Mar 15 00:12:25 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T6030
  Available memory (MB): 18432
  Available CPU cores: 12
Binaries:
  Node: 21.7.3
  npm: 10.5.0
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 14.2.2 // Latest available version is detected (14.2.2).
  eslint-config-next: 14.0.0
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.2.2
Next.js Config:
  output: N/A

Which example does this report relate to?

I do not know

What browser are you using? (if relevant)

123.0.6312.124

How are you deploying your application? (if relevant)

local machine and Vercel

Describe the Bug

When going through the https://nextjs.org/learn/dashboard-app tutorial I discovered a bug when editing an amount value in the "edit an invoice" portion. If you attempt to change the amount from anything to a value between 10.20 and 10.22 I removed the try catch block to generate this error message

image

Expected Behavior

You should be able to use the values between 10.20 and 10.22

To Reproduce

Edit an invoice and attempt to use any of the amounts 10.20, 10.21, 10.22

DusanJonjin commented 3 months ago

Yes, this error happens due to so called Javascript's floating point precision problem. This happens for numbers 0.1, 0.2, and even 0.05. Essentially, what happens here is that you are trying to write floating point numbers into Database which accepts only integers by default.

My solution was to extract and write a small function that makes sure the floating point error would not happen: const calcAmountInCents = (amount: number) => +(amount * 100).toFixed(); The plus sign is used to convert the value back to number because .toFixed() method returns a string.

You can use this function inside createInvoice and updateInvoice function in your lib/actions.ts file to get the amount in cents like this: const amountInCents = calcAmountInCents(amount);